Examples

Programming examples

Search short, complete examples by language and topic.

458 examples

Python Variables

Store and reuse values with clear names.

Python

Python arithmetic and operators

Calculate totals and distinguish division from floor division.

Python

Python Lists

Keep ordered values together.

Python

Python Functions

Package reusable behavior.

Python

Python decisions and boundaries

Choose one branch with if, elif, and else.

Python

Python loops and accumulators

Build a total one iteration at a time.

Python

Python while loops and digit processing

Repeat until a changing condition becomes false.

Python

Python nested loops and matrices

Visit every cell of a rectangular matrix.

Python

Python strings and palindrome checks

Normalize text before comparing characters.

Python

Python conversion and input validation

Convert text safely and handle invalid input.

Python

Python recursion and factorial

Separate a base case from a smaller recursive problem.

Python

Python files and context managers

Write and read a UTF-8 text file with automatic cleanup.

Python

Python classes and objects

Give each object its own state and methods.

Python

Python encapsulation and properties

Keep validation next to the state it protects.

Python

Python inheritance and polymorphism

Call overridden behavior through a common interface.

Python

Python abstraction with abstract classes

Specify required behavior while leaving implementation to subclasses.

Python

Python composition and object relationships

Build behavior by containing another object.

Python

Python algorithm complexity

Compare linear work with quadratic work by counting operations.

Python

Python sets and tuples

Choose uniqueness or immutable grouping to fit the problem.

Python

Python linear search

Find the first matching element without assuming sorted input.

Python

Python binary search

Halve a sorted search interval after each comparison.

Python

Python bubble sort

Move the largest remaining item to the end with adjacent swaps.

Python

Python selection sort

Select the smallest remaining value for each position.

Python

Python insertion sort

Grow a sorted prefix by shifting larger elements.

Python

Python merge sort

Sort halves recursively and merge them in order.

Python

Python quicksort and partitioning

Partition around a pivot, then sort smaller subproblems.

Python

Python stacks and balanced parentheses

Use last-in, first-out storage to match nested parentheses.

Python

Python queues with deque

Process work in first-in, first-out order.

Python

Python dictionaries and frequency counting

Count repeated values using key-value lookup.

Python

Python singly linked lists

Follow node references and insert at the head.

Python

Python binary search trees

Insert ordered keys and traverse them in sorted order.

Python

Python heaps and priority queues

Remove the smallest priority efficiently.

Python

Python graphs and breadth-first search

Visit reachable vertices level by level without revisiting cycles.

Python

Python depth-first search

Explore one branch fully before returning to alternatives.

Python

Python Dijkstra shortest paths

Relax nonnegative weighted edges using a priority queue.

Python

Python dynamic programming

Reuse earlier results instead of recomputing overlapping subproblems.

Python

Python backtracking and subsets

Choose, recurse, and undo to explore a decision tree.

Python

Growth rates and asymptotic notation

Count operations to see how logarithmic, linear, and quadratic work grow with input size.

Python

Recurrences and the master theorem

Describe divide-and-conquer cost with a recurrence and check it against its closed form.

Python

Amortized analysis

Show that an occasional expensive step still gives constant average cost per operation.

Python

Best, worst, and average case

Measure comparisons for lucky, unlucky, and typical inputs to the same algorithm.

Python

Correctness with loop invariants

Prove that insertion sort is correct by checking an invariant before every iteration.

Python

Time–space trade-offs with memoization

Spend memory on a cache to turn exponential recursion into linear work.

Python

The relational model and constraints

Define tables with keys and constraints so the database rejects invalid data.

Python

Querying with SELECT, GROUP BY, and HAVING

Filter rows, group them, filter the groups, and sort the results.

Python

Joins: combining tables

Match rows across tables with INNER and LEFT joins and keep rows that have no match.

Python

Normalization and update anomalies

Split a redundant table so each fact is stored once and updates cannot contradict themselves.

Python

Transactions and ACID

Group updates so they all happen or none do, and roll back when a rule fails.

Python

Indexes and query plans

See how an index changes a table scan into a search by reading the query plan.

Python

CPU scheduling: FCFS and shortest job first

Compare average waiting time when the scheduler runs jobs in arrival order or by shortest burst.

Python

Round-robin scheduling and the time quantum

Share the CPU fairly by running each job for at most one quantum, then rotating the queue.

Python

Page replacement: FIFO, LRU, and optimal

Count page faults for three replacement policies and see Belady's anomaly with FIFO.

Python

Deadlock avoidance with the banker's algorithm

Grant a resource request only if the resulting state is safe: every process can still finish.

Python

Synchronization: locks and the bounded buffer

Protect shared data with a lock and coordinate a producer and consumer with a blocking queue.

Python

Virtual memory: address translation with a page table

Split a virtual address into page number and offset and map it to a physical frame.

Python

Protocol layers and encapsulation

Wrap data in transport, network, and link headers on the way down and unwrap it on the way up.

Python

IP addressing, CIDR, and subnets

Read a prefix length, count addresses and usable hosts, and split a network into subnets.

Python

TCP sockets: a loopback echo server

Open a listening socket, connect a client, and exchange bytes over a reliable stream.

Python

UDP datagrams

Send independent datagrams with no connection and see how UDP differs from TCP.

Python

HTTP messages: requests, responses, and status codes

Read the text structure of an HTTP/1.1 request and response, and parse a response by hand.

Python

Forwarding with longest-prefix match

Choose the next hop by finding the most specific route that matches a destination address.

Python

Unit testing with unittest

Write small automated tests that check normal behavior, boundaries, and error handling.

Python

Refactoring safely with tests

Restructure code without changing its behavior, and prove that behavior is unchanged.

Python

SOLID design: depend on abstractions

Pass behavior into a class so it can be extended without being edited.

Python

The observer pattern and an event bus

Let a publisher notify many subscribers without knowing who they are.

Python

How version control works: commits, history, and merge bases

Model a commit graph as hashes and parents, and find the common ancestor used to merge branches.

Python

Contracts, invariants, and exceptions

State what a function requires and guarantees, and fail fast with clear errors.

Python

Cryptographic hashing and integrity

Compute SHA-256 digests and see why a one-character change produces a completely different hash.

Python

Storing passwords safely

Hash passwords with a unique salt and a deliberately slow function, then verify in constant time.

Python

Message authentication with HMAC

Attach a keyed tag to a message so that tampering is detected by anyone who holds the key.

Python

The one-time pad and why keys must never be reused

Use XOR as a cipher and see how reusing a key leaks the relationship between two messages.

Python

SQL injection and parameterized queries

See how string-built queries let input change the query, and how placeholders prevent it.

Python

Secure randomness for tokens and secrets

Generate unpredictable tokens with the secrets module, and see why the random module is not for security.

Python

Concurrency with thread pools for waiting work

Overlap tasks that mostly wait, such as network or disk requests, and keep results in order.

Python

Parallelism with processes for CPU-bound work

Split heavy computation across worker processes that run on separate cores.

Python

Speed-up limits: Amdahl's and Gustafson's laws

Compute how much faster a program can get when only part of it runs in parallel.

Python

MapReduce: word count in three phases

Express a computation as map, shuffle, and reduce steps that can run on many machines.

Python

Logical time: Lamport clocks

Order events across machines without a shared clock by counting events and message receipts.

Python

Replication and quorums

Read and write a majority of replicas so that every read overlaps the latest write.

Python

Intelligent agents and environments

Model an agent that perceives its environment and chooses actions, using a simple reflex vacuum cleaner.

Python

State-space search: the water jug problem

Formulate a puzzle as states, actions, and a goal, and find a shortest solution with breadth-first search.

Python

A* search with an admissible heuristic

Guide search toward the goal with a heuristic and compare how many cells it expands against uniform-cost search.

Python

Adversarial search: minimax and alpha-beta pruning

Choose moves in a two-player game and prune branches that cannot change the result.

Python

Constraint satisfaction: coloring a map

Assign values to variables so that every constraint holds, using backtracking search.

Python

Local search: hill climbing for the 8-queens puzzle

Improve a complete state step by step, and use restarts to escape local optima.

Python

Propositional logic and entailment by model checking

Decide whether a knowledge base entails a conclusion by checking every truth assignment.

Python

Forward chaining with definite clauses

Derive new facts from if-then rules until the query is proved or nothing new follows.

Python

Resolution and proof by refutation

Prove a conclusion by adding its negation to the clauses and deriving the empty clause.

Python

Semantic networks, inheritance, and default reasoning

Represent categories and properties as a network, and let specific knowledge override general defaults.

Python

First-order unification

Find the substitution that makes two logical terms identical, including the occurs check.

Python

Reasoning under uncertainty: Bayes' rule

Update beliefs with Bayes' rule and compute a posterior from a small Bayesian network by enumeration.

Python

Evaluating classifiers: accuracy, precision, recall, F1

Build a confusion matrix and see why accuracy alone can be misleading for rare classes.

Python

Linear regression with gradient descent

Fit a line by repeatedly stepping the parameters downhill on the squared error, and check it against the closed form.

Python

Logistic regression for classification

Turn a linear score into a probability with the sigmoid and train it by gradient descent on log loss.

Python

k-nearest neighbors and feature scaling

Classify by distance to stored examples, and see how an unscaled feature can dominate the result.

Python

Decision trees: entropy and information gain

Choose the feature that best splits the data by measuring how much it reduces uncertainty.

Python

k-means clustering

Group unlabelled points by alternating between assigning points to centroids and moving the centroids.

Python

Overfitting and cross-validation

Compare training accuracy with leave-one-out validation accuracy to choose k and detect memorization.

Python

The perceptron and linear separability

Train a single artificial neuron with the perceptron rule, and see why it cannot learn XOR.

Python

Activation functions and softmax

Compare sigmoid, tanh, and ReLU, and compute a numerically stable softmax.

Python

Multilayer networks: a forward pass that computes XOR

Combine two layers of neurons with hand-chosen weights to compute XOR, which one neuron cannot.

Python

Backpropagation: learning XOR by gradient descent

Compute gradients with the chain rule, verify them numerically, and train a small network on XOR.

Python

Cross-entropy loss and the softmax gradient

See why classification networks use cross-entropy, and verify its simple gradient numerically.

Python

Convolutional networks: output shapes and parameter counts

Compute how convolution and pooling change the size of an image, and why sharing weights saves parameters.

Python

Regularization: weight decay and dropout

Shrink weights with an L2 penalty, and see why inverted dropout keeps the expected activation unchanged.

Python

Images as arrays of pixels

Represent a grayscale image as rows of numbers, convert color to gray, and adjust brightness with clipping.

Python

Filtering images with convolution

Slide a small kernel over an image to blur it, and compute the valid output size.

Python

Edge detection with the Sobel operator

Estimate intensity gradients with two kernels and combine them into edge strength and direction.

Python

Thresholding with Otsu's method

Pick a threshold automatically by maximizing the separation between dark and bright pixel groups.

Python

Connected-component labeling

Find and number separate blobs in a binary image with a flood fill, and measure their sizes.

Python

Template matching with sum of squared differences

Find where a small pattern occurs in an image by sliding it over every position and scoring the match.

Python

C Variables

Declare typed values.

C

C Arrays

Store a fixed sequence.

C

C Pointers

Work with memory addresses.

C

C conditions, loops, and totals

Combine a counted loop with an even-number condition.

C

C strings and null terminators

Traverse characters without reading beyond the string.

C

C functions and pointer parameters

Modify caller-owned values through valid addresses.

C

C structures and records

Group related fields into a typed record.

C

C dynamic memory and ownership

Allocate, check, use, and free a heap buffer.

C

C reading and writing text files

Write lines to a file with fprintf, read them back with fgets, and parse each line with sscanf.

C

C bit manipulation and flags

Set, clear, test, and toggle bits with &, |, ^, ~, and shifts, and count set bits.

C

C two-dimensional arrays

Store a matrix, transpose it, and multiply it with another one.

C

C macros versus inline functions

See how a macro evaluates its arguments more than once and why a function is safer.

C

C array search with explicit length

Search only within the supplied array bounds.

C

C linked nodes and traversal

Connect records with pointers and follow a chain.

C

C array-based stacks and circular queues

Build a fixed-capacity stack and a queue that wraps around the end of its array.

C

C binary search and the standard bsearch

Find a value in a sorted array in logarithmic time, by hand and with the library function.

C

C sorting: bubble sort versus quicksort

Implement two sorts, count their comparisons, and see why O(n log n) beats O(n²).

C

C binary search trees with malloc and free

Allocate tree nodes dynamically, traverse them in order, and release every node.

C

C string algorithms

Write strlen and strcmp by hand, check palindromes, and count occurrences with strstr.

C

C dynamic programming: longest common subsequence

Fill a table of subproblem answers to find the longest sequence that two strings share.

C

C: best, worst, and average case of linear search

Count comparisons to see how the cost of one algorithm depends on the input it receives.

C

C: amortized cost of a growing array

Double the capacity of a malloc'd array when it fills, and count the copies made.

C

C: a hash index with chaining

Store keys in buckets of linked lists and see how collisions lengthen a lookup.

C

C: a sorted index and range queries with lower_bound

Use binary search on a sorted array to find the first key at or above a value and read a range from there.

C

C: simulating round-robin scheduling

Give each job a fixed time slice in turn and compute the turnaround time of each.

C

C: protecting a shared counter with a POSIX mutex

Run two threads that increment one counter and use pthread_mutex_lock so no update is lost.

C

C: the CRC-32 frame check sequence

Compute the cyclic redundancy check used by Ethernet and detect a single flipped bit.

C

C: network, broadcast, and host count of a CIDR block

Use shifts and masks on a 32-bit address to describe a subnet.

C

C: unit testing with a small macro

Report which checks pass and fail by printing the text of each expression.

C

C: the strategy pattern with function pointers

Choose behaviour at run time by passing a function to qsort, without changing the sorting code.

C

C: preventing buffer overflows with snprintf

Copy text into a fixed buffer without writing past its end, and detect truncation.

C

C: validating numeric input with strtol

Accept only text that is entirely a number in the allowed range, and reject everything else.

C

C: why a one-time pad key must never be reused

XOR two messages with the same key and show that the key cancels out and leaks information.

C

C: splitting a sum across threads without sharing

Give each thread its own range and result slot, then combine the results after joining.

C

C: the speed-up limit of Amdahl's law

Compute the best possible speed-up for a program in which only part of the work can run in parallel.

C

C: breadth-first search on a grid with an array queue

Find the length of the shortest path through a maze using a queue stored in a plain array.

C

C: game search with negamax and a memo table

Solve a take-away game and count how many positions memoization saves.

C

C: forward chaining with bit sets

Store facts as bits of an integer and apply if-then rules with bitwise operations.

C

C: resolution refutation with clauses as bit masks

Represent each clause by two masks, one for positive and one for negative literals, and resolve until a contradiction appears.

C

C: linear regression with gradient descent

Fit y = w·x + b by repeatedly stepping the parameters against the gradient of the mean squared error.

C

C: k-nearest-neighbors classification

Sort training points by distance to a query and let the k closest vote.

C

C: training a perceptron until it makes no mistakes

Use integer weights and the perceptron rule to learn the AND function.

C

C: softmax and why the largest score is subtracted

Convert scores to probabilities and show that the naive formula overflows for large scores.

C

C: smoothing noise with a box-blur convolution

Average each 3×3 neighbourhood of a small image to reduce an isolated bright pixel.

C

C: grayscale histogram and a global threshold

Count how many pixels have each brightness level and separate dark from bright pixels at the mean.

C

C++ Basics

Write and run a first program.

C++

C++ conditions and range loops

Filter a sequence while accumulating a result.

C++

C++ functions and references

Use a reference parameter to update a caller's value.

C++

C++ recursive factorial

Trace recursive calls and their return values.

C++

C++ strings and string streams

Use std::string, parse text with getline and istringstream, and convert between text and numbers.

C++

C++ references, const, and auto

Pass large objects without copying, protect them with const, and let the compiler deduce types.

C++

C++ lambdas and the standard algorithms

Sort, search, count, transform, and remove elements with algorithms and small anonymous functions.

C++

C++ Classes

Group data and behavior.

C++

C++ constructors and encapsulation

Initialize private state and expose a controlled interface.

C++

C++ abstract classes and virtual dispatch

Invoke derived behavior through a base reference.

C++

C++ composition and RAII

Let owned members manage their resources automatically.

C++

C++ function templates

Reuse one type-checked algorithm for different types.

C++

C++ inheritance and virtual functions

Call the right method through a base-class pointer, and see what slicing does.

C++

C++ operator overloading

Give a Vec2 class natural arithmetic, comparison, and output operators.

C++

C++ smart pointers and ownership

Use unique_ptr for single ownership, shared_ptr for shared ownership, and weak_ptr to observe.

C++

C++ vectors and iterator invalidation

Grow a dynamic array and use checked access.

C++

C++ binary search with lower_bound

Find an insertion position and check whether it is a match.

C++

C++ stack and queue adapters

Compare LIFO and FIFO removal on the same values.

C++

C++ ordered maps and frequencies

Count keys and traverse them in sorted order.

C++

C++ linked lists with unique ownership

Build a node chain with automatic destruction.

C++

C++ sorting: insertion sort, merge sort, and std::stable_sort

Write two sorts by hand and sort records with a comparator, keeping equal items in order.

C++

C++ singly linked list with unique_ptr

Own each node with a unique_ptr, push at the front, reverse the list, and let destructors do the cleanup.

C++

C++ binary search tree traversals

Insert values into a BST and visit them depth-first and level by level.

C++

C++ priority_queue and the top-k pattern

Use a binary heap to get the smallest element quickly, and keep the k largest values of a stream.

C++

C++ graphs: BFS, DFS, and connected components

Store a graph as adjacency lists, visit it breadth-first and depth-first, and count its components.

C++

C++: best, worst, and average case of linear search

Count comparisons to see that one algorithm can have different costs on different inputs.

C++

C++: amortized cost of a growing array

Count the copies made by a doubling array to see why push_back is amortized constant time.

C++

C++: a hash join with unordered_map

Join two tables by building a hash table on one and probing it with each row of the other.

C++

C++: an ordered index with std::map

Answer range and nearest-key queries with lower_bound and upper_bound.

C++

C++: page replacement with FIFO and LRU

Count page faults for two replacement policies and see Belady's anomaly.

C++

C++: protecting shared data with std::mutex

Run two threads that increment one counter and use a lock to keep every update.

C++

C++: the Internet checksum

Compute the 16-bit ones'-complement checksum used by IP, TCP, and UDP, and use it to detect corruption.

C++

C++: forwarding with longest-prefix match

Pick the most specific route that matches a destination address, as a router does.

C++

C++: a small unit-test harness

Check results and expected exceptions with a macro and a template, and report failures.

C++

C++: the observer pattern with std::function

Notify any number of listeners without the publisher knowing what they do.

C++

C++: preventing buffer overflows with bounds checks

Reject writes that do not fit in a buffer and use at() so out-of-range reads fail safely.

C++

C++: validating untrusted input with std::from_chars

Parse a port number strictly and reject anything that is not exactly a number in range.

C++

C++: splitting a sum across std::async tasks

Run two halves of a computation concurrently and combine the results with futures.

C++

C++: lock-free counting with std::atomic

Increment a shared counter from four threads without a mutex.

C++

C++: A* search with a Manhattan-distance heuristic

Guide a shortest-path search with an estimate of the remaining distance.

C++

C++: minimax with alpha-beta pruning

Search a game tree and skip branches that cannot change the result.

C++

C++: entailment by enumerating models

Test whether a knowledge base entails a query by checking every truth assignment.

C++

C++: backward chaining from a goal

Prove a goal by finding a rule that concludes it and then proving that rule's conditions.

C++

C++: linear regression with gradient descent

Fit y = w·x + b by repeatedly moving the parameters against the gradient of the mean squared error.

C++

C++: k-means clustering

Group unlabeled points by alternating between assigning points to centers and moving centers to the mean.

C++

C++: a perceptron learns OR but not XOR

Train the same neuron on two gates and compare the accuracy it can reach.

C++

C++: stable softmax and cross-entropy loss

Turn raw scores into probabilities, measure the loss, and avoid overflow.

C++

C++: convolution with zero padding

Apply a Laplacian kernel so the output has the same size as the input and responds to a single bright pixel.

C++

C++: grayscale conversion and thresholding

Convert color pixels to brightness with luminance weights and split them into foreground and background.

C++

Java Basics

Start with a class and main method.

Java

Java conditions, arrays, and loops

Count values that satisfy a boundary condition.

Java

Java methods and exception handling

Separate conversion errors from valid numeric values.

Java

Java recursion and bounded factorial

Use a base case and validate the representable range.

Java

Java variables, types, and casting

Declare typed variables and understand integer division, overflow, and conversions.

Java

Java arrays and strings

Work with fixed-size arrays, common String methods, and the difference between == and equals.

Java

Java method overloading, varargs, and pass by value

Declare several methods with the same name and see what a method can and cannot change.

Java

Java constructors and encapsulation

Initialize private fields and validate changes through methods.

Java

Java inheritance and method overriding

Use a superclass reference to call subclass behavior.

Java

Java interfaces and composition

Depend on a contract and inject a collaborating object.

Java

Java abstract classes and enums

Define a shared base with an abstract method, and a fixed set of constants with fields.

Java

Java generics and bounded types

Write one class and one method that work for many types while the compiler checks them.

Java

Java equals, hashCode, and toString

Define when two objects are equal so that they work correctly in sets and maps.

Java

Java ArrayList and generics

Use a resizable, type-checked sequence.

Java

Java binary search and interval bounds

Implement logarithmic search on an ascending array.

Java

Java stacks and balanced brackets

Use a stack to check that brackets are properly nested.

Java

Java ArrayDeque as a queue

Choose queue operations with explicit empty-queue behavior.

Java

Java maps, sets, and duplicate counting

Track counts and distinct values with separate collection roles.

Java

Java singly linked lists

Build a list of nodes by hand, insert at the front and the back, and reverse it.

Java

Java binary search trees

Insert values into a tree that keeps smaller values on the left, and traverse it in sorted order.

Java

Java sorting: insertion sort, merge sort, and comparators

Implement two sorts by hand and sort objects with a Comparator.

Java

Java priority queues and heaps

Always remove the smallest (or largest) item, and find the k largest values.

Java

Java: counting operations to see growth rates

Count loop iterations instead of timing them to compare linear, quadratic, and logarithmic growth.

Java

Java: amortized cost of a growing array

Show that doubling a backing array makes append cost O(1) on average even though some appends copy everything.

Java

Java: a hash join and why it beats a nested loop

Join two collections by building a hash table on one side and probing it with the other.

Java

Java: an ordered index with TreeMap

Use a sorted map the way a database uses an ordered index to answer range and nearest-key queries.

Java

Java: simulating round-robin CPU scheduling

Rotate jobs through a ready queue with a fixed time slice and record when each one finishes.

Java

Java: mutual exclusion with synchronized

Protect a shared counter from lost updates when two threads increment it.

Java

Java: a TCP echo server on the loopback interface

Open a server socket on an ephemeral port and connect to it with a client socket in the same program.

Java

Java: IPv4 addresses, masks, and CIDR blocks

Compute the network address, broadcast address, and host count of a subnet with bitwise operations.

Java

Java: testing a method with a tiny test runner

Check normal cases, boundaries, and error cases, and report which ones pass.

Java

Java: strategy and observer with interfaces and lambdas

Swap behavior behind an interface and notify listeners without coupling the sender to them.

Java

Java: SHA-256 hashing for integrity

Compute a SHA-256 digest with MessageDigest and see that a tiny change produces a completely different value.

Java

Java: storing passwords with a salt and PBKDF2

Derive a password hash with a random salt and many iterations, then verify a login attempt.

Java

Java: splitting work across a thread pool

Divide a sum into chunks, run them on an ExecutorService, and combine the Future results.

Java

Java: parallel streams and CompletableFuture

Count items with a parallel stream and combine two asynchronous results.

Java

Java: breadth-first search for a shortest path

Search a grid with a queue to find the fewest moves from the start to the goal around walls.

Java

Java: game-tree search with minimax (negamax)

Search every move in a take-away game to find which positions are winning for the player to move.

Java

Java: propositional entailment by model checking

Enumerate every truth assignment to decide whether a knowledge base entails a query.

Java

Java: forward chaining with if-then rules

Repeatedly apply rules whose conditions are known until no new facts can be derived.

Java

Java: linear regression with gradient descent

Fit a straight line to data by repeatedly stepping the weights against the gradient of the squared error.

Java

Java: k-nearest-neighbors classification

Classify a point by letting its k closest training points vote.

Java

Java: training a perceptron to learn AND

Update the weights of a single neuron with the perceptron rule until it classifies all four inputs correctly.

Java

Java: a two-layer network that computes XOR

Combine two hidden neurons so that a network solves the problem a single perceptron cannot.

Java

Java: filtering an image with a convolution kernel

Slide a 3×3 averaging kernel over a small grayscale image to smooth it.

Java

Java: finding edges with the Sobel operator

Estimate the horizontal intensity change at each pixel and mark strong edges.

Java

JavaScript Variables

Use const and let for values.

JavaScript

JavaScript Functions

Write reusable logic.

JavaScript

JavaScript conditions and array loops

Filter values with strict comparisons and accumulate a total.

JavaScript

JavaScript map, filter, and reduce

Build a transformation pipeline without mutating the source.

JavaScript

JavaScript types, equality, and coercion

Know the primitive types, why === is safer than ==, and which values count as false.

JavaScript

JavaScript closures and scope

Use a function that remembers its surrounding variables, and see why let fixes the classic loop bug.

JavaScript

JavaScript destructuring, spread, and rest

Unpack objects and arrays into variables, copy with spread, and collect arguments with rest.

JavaScript

JavaScript string methods and regular expressions

Split, pad, replace, and extract parts of text with strings and regular expressions.

JavaScript

JavaScript promises, async, and await

Write asynchronous code that reads like synchronous code, and handle errors with try and catch.

JavaScript

JavaScript classes and private fields

Protect instance state with a private class field.

JavaScript

JavaScript inheritance and overriding

Reuse initialization and specialize instance behavior.

JavaScript

JavaScript prototypes and class inheritance

See that classes are built on prototype chains, and extend one constructor from another.

JavaScript

JavaScript private fields, getters, and static members

Hide state with #private fields, expose it through a getter, and keep a counter on the class itself.

JavaScript

JavaScript binary search

Search a sorted numeric array with a shrinking interval.

JavaScript

JavaScript Map and Set

Count values and identify distinct entries.

JavaScript

JavaScript linked lists and iterators

Build a singly linked list class that can be looped over with for...of.

JavaScript

JavaScript stacks and queues

Use an array as a stack, and write a queue that does not shift the whole array on every removal.

JavaScript

JavaScript sorting and the default sort pitfall

Learn why [10, 9, 1].sort() is wrong, sort with comparators, and write a merge sort.

JavaScript

JavaScript binary search trees with a generator

Insert values, search, and produce the sorted order lazily with a recursive generator.

JavaScript

JavaScript graphs: BFS, DFS, and path existence

Store a graph as a Map of neighbour lists and search it breadth-first and depth-first.

JavaScript

JavaScript: memoization trades memory for time

Count the calls made by a naive recursive Fibonacci and a memoized one.

JavaScript

JavaScript: counting the steps of binary search

Show that searching a sorted array of 1000 items takes at most about ten comparisons.

JavaScript

JavaScript: an index turns a scan into a lookup

Compare scanning an array for a row with looking it up in a Map keyed by id.

JavaScript

JavaScript: GROUP BY and HAVING with Map

Total a column per group, keep the groups that pass a condition, and sort them.

JavaScript

JavaScript: the event loop as a cooperative scheduler

Predict the order in which synchronous code, nextTick, promises, and timers run in Node.js.

JavaScript

JavaScript: LRU replacement with a Map

Use Map's insertion order to evict the least recently used page and count page faults.

JavaScript

JavaScript: an HTTP server and client on the loopback interface

Start a Node.js HTTP server on a free port and request it with fetch to see status codes.

JavaScript

JavaScript: a TCP echo server with the net module

Send a line through a TCP socket and print the server's reply.

JavaScript

JavaScript: unit tests with node:assert

Write small tests with assertions, including checks that bad input throws the right error.

JavaScript

JavaScript: the observer pattern with EventEmitter

Let several listeners react to the same event without the emitter knowing about them.

JavaScript

JavaScript: SHA-256 hashing and HMAC with node:crypto

Hash a message, authenticate it with a secret key, and compare tags in constant time.

JavaScript

JavaScript: storing passwords with scrypt and a salt

Derive a memory-hard hash from a password and a random salt, then verify a login attempt.

JavaScript

JavaScript: preventing XSS by escaping output

Turn special HTML characters into entities so user text is shown as text, never run as markup.

JavaScript

JavaScript: concurrency without parallelism

See how async functions interleave on a single thread and finish together under Promise.all.

JavaScript

JavaScript: real parallelism with worker threads

Split an array between two worker threads and add their partial results.

JavaScript

JavaScript: breadth-first search for the fewest steps

Find a shortest path in an unweighted graph by exploring it layer by layer.

JavaScript

JavaScript: constraint satisfaction by backtracking

Color a map so that neighbouring regions differ, counting every valid coloring.

JavaScript

JavaScript: querying facts stored as triples

Represent knowledge as subject–predicate–object triples and answer queries with variables.

JavaScript

JavaScript: proof by resolution refutation

Show that a knowledge base entails a query by deriving a contradiction from the knowledge base plus the negated query.

JavaScript

JavaScript: fitting a line with least squares

Compute the slope, intercept, and R² of the best-fit line in closed form.

JavaScript

JavaScript: a naive Bayes text classifier

Classify short messages as spam or ham from word counts with Laplace smoothing.

JavaScript

JavaScript: a forward pass through two dense layers

Multiply by weight matrices, add biases, apply ReLU, and finish with softmax probabilities.

JavaScript

JavaScript: checking a gradient numerically

Compare a hand-derived gradient with a finite-difference estimate, the standard test for backpropagation code.

JavaScript

JavaScript: RGBA pixel arrays and Uint8ClampedArray

Convert pixels stored the way a canvas stores them to grayscale and see how clamping works.

JavaScript

JavaScript: a sharpen filter and why clamping matters

Apply a sharpening kernel to a step edge and see the overshoot clamped to the valid range.

JavaScript

TypeScript Types

Describe values before runtime.

TypeScript

TypeScript Union Types and Narrowing

Accept more than one type and narrow it safely with typeof.

TypeScript

TypeScript literal types and as const

Build a union of allowed strings from an object or array and make switch statements exhaustive.

TypeScript

TypeScript unknown and user-defined type guards

Validate parsed JSON at run time and let the compiler trust the result only after the check.

TypeScript

TypeScript tuples, readonly, and optional chaining

Return fixed-shape pairs, protect arrays from change, and read nested optional values safely.

TypeScript

TypeScript Interfaces

Describe the shape of an object, including optional properties.

TypeScript

TypeScript abstract classes and access modifiers

Use private, protected, readonly, and abstract to describe what subclasses and outside code may do.

TypeScript

TypeScript Generics

Write one function that keeps the type of whatever it receives.

TypeScript

TypeScript generic stack and queue

Write containers that work for any element type and keep it checked.

TypeScript

TypeScript generic binary search tree

Order any type with a comparator function and collect the values in sorted order.

TypeScript

TypeScript typed comparators and multi-key sorting

Build comparators from a key with keyof, and combine them to sort by several fields.

TypeScript

TypeScript: a typed memoize wrapper

Cache the results of a pure function with a generic higher-order function and count how often the body runs.

TypeScript

TypeScript: type-safe select, where, and orderBy

Write small query helpers whose column names are checked by the compiler with keyof.

TypeScript

TypeScript: a process lifecycle as a typed state machine

Allow only legal transitions between process states and reject the rest.

TypeScript

TypeScript: parsing a raw HTTP request into a typed object

Split the request line, headers, and body of an HTTP/1.1 message and read a query parameter.

TypeScript

TypeScript: explicit errors with a Result type

Return success or failure as a value, and let the compiler force the caller to handle both.

TypeScript

TypeScript: branded types for validated and escaped data

Use the type system so that unvalidated text cannot be passed where a validated value is required.

TypeScript

TypeScript: running async tasks with a concurrency limit

Start at most N tasks at once, collect results in input order, and measure the peak concurrency.

TypeScript

TypeScript: a generic breadth-first search solves the water-jug puzzle

Write the search once for any state type and apply it to two jugs.

TypeScript

TypeScript: propositional formulas as a discriminated union

Represent formulas as trees, evaluate them for any assignment, and test for tautologies.

TypeScript

TypeScript: precision, recall, and F1 from a confusion matrix

Count true and false positives and negatives with a typed interface, then compute the metrics.

TypeScript

TypeScript: composing neural-network layers behind an interface

Build a small network from Dense and Sigmoid layers that share one Layer interface.

TypeScript

TypeScript: a grayscale image class with threshold and flip

Wrap a flat pixel buffer in a class that checks bounds and returns new images from its operations.

TypeScript

HTML Elements

Structure a document with semantic tags.

HTML

HTML Forms

Collect input with labelled form controls.

HTML

HTML Lists and Tables

Mark up lists and tabular data with the right elements.

HTML

HTML Links and Images

Connect pages and show pictures with alternative text.

HTML

HTML Semantic Page Layout

Describe the regions of a page with header, nav, main, article, aside, and footer.

HTML

HTML Accessibility Basics

Make pages usable with keyboards and screen readers through labels, alt text, and landmarks.

HTML

HTML Document Head and Metadata

Set the character encoding, viewport, title, description, and stylesheet for a page.

HTML

HTML Responsive Images and Media

Offer different image files for different screens and embed video with a fallback.

HTML

HTML Forms: GET versus POST

See what each form method sends over HTTP and when to use it.

HTML

HTML Safe Links, Embeds, and Content Security Policy

Limit what linked and embedded content can do with rel, sandbox, and a content security policy.

HTML

CSS Selectors

Choose elements and apply styles.

CSS

CSS Box Model

Understand content, padding, border, and margin.

CSS

CSS Flexbox

Lay out items in a row with spacing and alignment.

CSS

CSS Variables and Media Queries

Reuse values and adapt the layout to narrow screens.

CSS

CSS Specificity and the Cascade

Predict which rule wins when several rules match the same element.

CSS

CSS Grid Layout

Build a two-dimensional page layout with named areas and a responsive card grid.

CSS

CSS Transitions, Animations, and Reduced Motion

Animate state changes smoothly and respect users who prefer less motion.

CSS

CSS Units and Fluid Typography

Choose relative units and clamp() so text scales with the user's settings and the screen.

CSS

SQL SELECT

Read rows from a table.

SQL

SQL Aggregates and GROUP BY

Summarize many rows into one row per group.

SQL

SQL Joins

Combine rows from two tables that share a key.

SQL

SQL INSERT, UPDATE, and DELETE

Add, change, and remove rows, then check the result.

SQL

SQL: constraints keep the data valid

Use PRIMARY KEY, NOT NULL, UNIQUE, CHECK, and REFERENCES so the database itself rejects bad rows.

SQL

SQL: transactions with COMMIT and ROLLBACK

Move money between two accounts so that both updates happen or neither does.

SQL

SQL: normalization removes repeated facts

Split a table that repeats a customer's city on every row into two tables and see why one update is enough.

SQL

SQL: subqueries and common table expressions

Compare each row with a group average, and name an intermediate result with WITH.

SQL

SQL: window functions for running totals and ranks

Compute a running total and a rank within each group without collapsing the rows.

SQL

SQL: views and triggers

Name a reusable query as a view and record price changes automatically with a trigger.

SQL

SQL: a unique index and the system catalog

Enforce uniqueness with an index and look up the index in the database's own catalog.

SQL

C# Basics

Print a value from a .NET program.

C#

C# Loops

Repeat an action with a for loop.

C#

C# Methods

Package reusable logic in a static method.

C#

C# strings and formatting

Use common string methods, compare text correctly, and format numbers with format specifiers.

C#

C# exceptions, finally, and using

Throw and catch a custom exception, filter by condition, and release resources reliably.

C#

C# nullable values, patterns, and switch expressions

Handle missing values safely and branch on the type and value of an object.

C#

C# Classes and Properties

Protect state with a property that only the class can change.

C#

C# inheritance, virtual, and abstract members

Override behaviour in subclasses and call it through a base-type reference.

C#

C# records, with-expressions, and value semantics

Create immutable data types with value equality, copy them with changes, and compare with structs and classes.

C#

C# delegates, events, and lambdas

Pass behaviour as a value and let objects notify subscribers when something happens.

C#

C# Lists

Grow a collection with List<T> and add its values.

C#

C# Dictionary and HashSet operations

Count words with a dictionary and combine sets with union, intersection, and difference.

C#

C# Stack and Queue: evaluating postfix expressions

Use a stack to evaluate expressions written in reverse Polish notation and a queue for first-in order.

C#

C# sorting, stability, and Array.BinarySearch

Sort arrays and records, keep equal items in order with LINQ, and find insertion points.

C#

C# LRU cache with Dictionary and LinkedList

Combine a hash table and a doubly linked list so that get, put, and eviction all take constant time.

C#

C# generic binary search tree with IEnumerable

Constrain the element type with IComparable<T> and expose the sorted values with yield return.

C#

C#: best and worst case of insertion sort

Count comparisons on sorted, reversed, and mixed input to see how input order changes the cost.

C#

C#: watching List<T> grow geometrically

Observe the capacity of a List<int> as items are added and see that reallocations become rarer.

C#

C#: relational queries with LINQ join and group

Join two collections on a key, sort the result, and aggregate it by group, as SQL does.

C#

C#: an ordered index with SortedSet

Answer range, minimum, maximum, and nearest-value queries on sorted keys.

C#

C#: first-come-first-served versus shortest-job-first

Compare the average waiting time of two scheduling policies for the same set of jobs.

C#

C#: protecting shared state with lock

Start two threads that update one counter and use lock so that no update is lost.

C#

C#: a TCP echo server on the loopback interface

Use TcpListener and TcpClient with async methods to send a line and read the reply.

C#

C#: IPv4 subnets with IPAddress and bit masks

Compute the network and broadcast addresses for a CIDR block and test whether addresses belong to it.

C#

C#: testing values and exceptions with a small harness

Check results, and verify that bad input throws the expected exception type.

C#

C#: dependency injection makes code testable

Pass a dependency in through the constructor so tests can replace it with a fixed one.

C#

C#: message authentication with HMAC-SHA256

Compute a keyed tag so a receiver can detect tampering, and compare tags safely.

C#

C#: password storage with a salt and PBKDF2

Derive a slow salted hash from a password and verify a login attempt in constant time.

C#

C#: running tasks in parallel with Task.WhenAll

Start independent computations as tasks and await all of their results.

C#

C#: Parallel.For with Interlocked

Spread loop iterations over cores and combine results safely with an atomic add.

C#

C#: uniform-cost search with PriorityQueue

Find the cheapest route from a start node to every other node in a weighted graph.

C#

C#: solving tic-tac-toe with minimax

Search the complete game tree and show that perfect play by both sides ends in a draw.

C#

C#: first-order unification

Find a substitution that makes two logical terms identical, including the occurs check.

C#

C#: semantic networks with default reasoning

Inherit properties up an is-a hierarchy and let more specific nodes override defaults.

C#

C#: logistic regression for classification

Predict a probability with the sigmoid function and train the weights by gradient descent.

C#

C#: entropy and information gain for decision trees

Measure how much a feature reduces uncertainty about a label, the criterion used to choose a split.

C#

C#: backpropagation learns XOR

Train a 2-2-1 sigmoid network by gradient descent until it computes XOR.

C#

C#: activation functions and their ranges

Compare sigmoid, tanh, and ReLU on the same inputs.

C#

C#: Sobel gradient magnitude on a diagonal edge

Combine horizontal and vertical Sobel responses into one edge-strength value.

C#

C#: the integral image (summed-area table)

Precompute running sums so that the total of any rectangle takes four lookups.

C#

Go Basics

Print a message from main.

Go

Go Functions and Multiple Return Values

Return more than one value from a function.

Go

Go Loops

Count with the for statement.

Go

Go Structs and Methods

Group fields in a struct and attach behavior to it.

Go

Go Slices

Grow a sequence with append and take a part of it.

Go

Rust Basics

Bind values and print them.

Rust

Rust Ownership

Borrow a string without moving it.

Rust

Rust Variables, Mutability, and Shadowing

Bindings are immutable by default; mut and shadowing change that.

Rust

Rust Enums and match

Model alternatives with an enum and handle each one with match.

Rust

Rust Vectors

Store a growable list with Vec and sum it with an iterator.

Rust

Kotlin Basics

Use values and string templates.

Kotlin

Kotlin Lists

Process an ordered collection.

Kotlin

Kotlin Functions

Declare typed parameters and a return type.

Kotlin

Kotlin when Expressions

Choose a result from several conditions with when.

Kotlin

Kotlin null safety

Distinguish nullable from non-null types, and use ?., ?:, let, and !! deliberately.

Kotlin

Kotlin collections and higher-order functions

Filter, map, group, sort, and fold lists with lambdas instead of loops.

Kotlin

Kotlin Classes

Declare a class with a primary constructor and private state.

Kotlin

Kotlin data classes and sealed interfaces

Model alternatives with a sealed hierarchy and let the compiler check that every case is handled.

Kotlin

Kotlin object, companion object, and delegation

Create singletons, class-level factories with private constructors, and reuse behaviour by delegating to an interface.

Kotlin

Kotlin sorting and binary search

Sort lists with sorted and sortedBy, and find a value or its insertion point with binarySearch.

Kotlin

Kotlin ArrayDeque as a stack and a queue

Check balanced brackets with a stack and serve items in arrival order with a queue.

Kotlin

Kotlin maps: counting and indexing

Count words with groupingBy and build a lookup map with getOrPut.

Kotlin

Kotlin unit tests with lambdas and runCatching

Write a minimal test function that reports passes and failures, including expected exceptions.

Kotlin

Kotlin SHA-256 and PBKDF2 on the JVM

Hash text with MessageDigest and derive a salted password hash with PBKDF2.

Kotlin

Kotlin threads, AtomicInteger, and an executor

Start threads that update a shared counter safely and split a sum across a thread pool.

Kotlin

Ruby Basics

Store text and print it.

Ruby

Ruby Arrays

Visit each value in an array.

Ruby

Ruby Methods and map

Define a method and transform an array with map.

Ruby

Ruby Classes

Keep state in an instance variable and read it with attr_reader.

Ruby

Ruby Hashes

Store key-value pairs and iterate over them.

Ruby

PHP Basics

Print a value from a PHP script.

PHP

PHP Arrays

Loop through an indexed array.

PHP

PHP Functions

Declare typed parameters and return values.

PHP

PHP strings, sprintf, and regular expressions

Format text with sprintf, split and join strings, and match patterns with preg functions.

PHP

PHP strict types, match, and the nullsafe operator

Use union types, a match expression, constructor promotion, and ?-> to write safer code.

PHP

PHP closures, array functions, and generators

Transform arrays with map, filter, and reduce, capture variables in closures, and produce values lazily with yield.

PHP

PHP Classes

Hide a property and change it only through methods.

PHP

PHP interfaces, traits, and abstract classes

Share a contract with an interface, share code with a trait, and share both with an abstract base.

PHP

PHP Associative Arrays

Map names to values and loop over keys and values.

PHP

PHP sorting, usort, and the spaceship operator

Sort arrays by value or by custom rules, and combine several sort keys with <=>.

PHP

PHP SPL data structures: stack, queue, and heap

Use the standard SplStack, SplQueue, SplMinHeap, and SplPriorityQueue classes.

PHP

PHP unit tests with closures

Write a tiny test runner with named test closures and check normal values and expected errors.

PHP

PHP password_hash, password_verify, and hash_hmac

Store passwords with bcrypt through the built-in API and sign messages with HMAC.

PHP

PHP preventing XSS with htmlspecialchars

Encode user text before printing it into HTML, and escape for the right context.

PHP

Swift Basics

Bind a constant and print it.

Swift

Swift Functions and Argument Labels

Use default values and argument labels to make calls readable.

Swift

Swift Optionals

Handle values that might be missing with if let.

Swift

Swift Structs

Model data with a struct, which is copied when assigned.

Swift

Swift Arrays

Grow an array and combine its values with reduce.

Swift

Scala Basics

Run a small program with an entry point.

Scala

Scala Functions as Values

Define a method and pass it to a higher-order function.

Scala

Scala Case Classes and Pattern Matching

Define a data class and take it apart with match.

Scala

Scala Collections: map and filter

Transform and filter an immutable List without loops.

Scala

Scala Maps and Option

Look up a key without nulls by using Option.

Scala

Lua Basics

Store a local value and print it.

Lua

Lua Functions

Write a local function that loops over a table and returns a result.

Lua

Lua Loops

Count with a numeric for and repeat with while.

Lua

Lua Tables

Use one table type as both an array and a record.

Lua

Perl Basics

Declare a scalar and print it.

Perl

Perl Subroutines

Define a sub that reads its arguments from @_.

Perl

Perl regular expressions and text processing

Capture named groups, collect all matches, transliterate characters, and compute replacements with /e.

Perl

Perl references and nested data structures

Build hashes of arrays, add to them, and loop over them with references.

Perl

Perl file handles on strings and formatted output

Read lines from a string as if from a file, validate each line, and write formatted output to a string.

Perl

Perl subroutines, context, and closures

Return different results in list and scalar context, build closures, and write a recursive anonymous function.

Perl

Perl packages, bless, and inheritance

Create objects as blessed hashes, override methods in a subclass, and call the parent version.

Perl

Perl Arrays

Store a list in an @array and loop over it.

Perl

Perl Hashes

Map keys to values and print them in a stable order.

Perl

Perl sort blocks and the Schwartzian transform

Sort numbers, hash keys by value, and records by computed keys without recomputing the keys.

Perl

Perl stacks, queues, and word frequencies

Use push, pop, shift, and unshift as stack and queue operations, and count items with a hash.

Perl

Perl SHA-256 and HMAC with Digest::SHA

Hash messages, authenticate them with a key, and compare tags without leaking timing.

Perl