Combinatorics basics
Beginner · 9 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Combinatorics is the art of counting possibilities without listing them: how many outfits, passwords, seat arrangements or teams are possible. It tells you early whether a try-everything approach is fine or hopeless, and how strong a secret really is.
Practical use cases
- Web app: How strong is a 6-digit PIN?. A banking app lets users choose a 6-digit PIN. Each of the 6 positions has 10 choices, so there are 10 times 10 six times, which is a million PINs. That tells the security team to lock the account after a few wrong tries, since an attacker could otherwise test them all quickly.
- Web app: Product variant matrix. A clothing store sells a shirt in 5 sizes, 8 colours and 3 fits. Multiplying gives 120 variants, each needing its own stock row and photo. Counting before building reveals that the inventory table will be much bigger than the product list suggests.
- System: Test planning. A form with 10 on or off settings has 1,024 combinations. Testers cannot try them all, so counting tells them to pick pairs and risky combinations rather than everything. Counting first shows how big the problem really is.
The story: The Wedding Thali Puzzle
At a cousin's wedding, the caterer announced the menu: 3 starters, 2 main dishes and 4 desserts. "A thali is one of each," he said. Mira whispered to Kabir, "How many different thalis can they make?" Kabir drew a table. For each of the 3 starters there are 2 mains, and for each of those 4 desserts: 3 × 2 × 4 = 24 thalis. That is the multiplication rule: independent choices multiply.
Later, the photographer asked three cousins to stand in a line. Who stands first? 3 choices. Second? 2 left. Third? 1 left. 3 × 2 × 1 = 6 ways. When the order matters, we are counting arrangements (permutations), and the pattern 3 × 2 × 1 is called a factorial, written 3!.
The cricket team was another puzzle. Aarav must pick any 2 friends from 4. Here, A with B is the same team as B with A, because order does not matter, so we count selections (combinations). Listing them: AB, AC, AD, BC, BD, CD = 6. Arrangements would give 12; every team got counted twice, so divide by 2.
So three questions guide you. Do the choices stack up (multiply)? Does the order matter (arrangement)? Or only who is chosen (selection)? Answer those, and you can count huge numbers of possibilities without listing a single one. Later, backtracking will list them, but counting tells you how many to expect.
How to spot this problem, and where you need it
You need to know how many ways something can be arranged, chosen or combined, either to size a database, judge security, or check that trying every option is practical.
Signs you need it
- The question says how many ways, how many combinations, how many orders or how many different passwords.
- Each choice multiplies the number of results, such as options on a product, filters on a search page or settings on a form.
- A brute-force or backtracking approach seems natural, but you are not sure whether it will finish in time.
Where to use it in a project
- Estimating the size of variant tables, filter combinations or cached pages before designing a database schema.
- Judging password, PIN and coupon-code strength and choosing sensible lockout and rate limits.
The solution
First decide whether order matters. If choices are made one after another, multiply the number of options at each step. If you pick several items and the order matters, shrink the options by one each time. If order does not matter, take that count and divide by the number of ways to reorder the picked items. Do this on paper first, then decide whether listing them all is realistic.
Payoff: Before: guessing that a 6-digit PIN is safe. After: knowing there are exactly 1,000,000 and setting a lockout after 5 tries.
Explain it like I am 8
If you have 3 T-shirts and 2 pairs of shorts, you can make 3 × 2 = 6 outfits. Lining up friends for a photo gives lots of orders. But picking who joins your team only cares who is picked, not who stands first.
How it works, step by step
- Multiplication rule: if you make independent choices (3 starters, then 2 mains), multiply the options.
- Arrangements (order matters): n things in a line can be ordered in
n × (n-1) × ... × 1ways (n factorial). - Choose k of n in order: multiply the first k terms:
n × (n-1) × ... (k terms). - Selections (order ignored): take the ordered count and divide by the
k!orderings of the chosen team. - Ask first: does swapping two picks give a different outcome? If yes, it is an arrangement; if no, a selection.
The code in four languages
PHP
<?php
function factorial(int $n): int {
$f = 1;
for ($i = 2; $i <= $n; $i++) $f *= $i;
return $f;
}
// Arrangements: pick k from n, order matters.
function arrangements(int $n, int $k): int {
$r = 1;
for ($i = 0; $i < $k; $i++) $r *= ($n - $i);
return $r;
}
// Selections: pick k from n, order ignored.
function choose(int $n, int $k): int {
$r = 1;
for ($i = 1; $i <= $k; $i++) {
$r = intdiv($r * ($n - $k + $i), $i); // stays a whole number each step
}
return $r;
}
echo "Thalis: " . (3 * 2 * 4) . "
"; // 24
echo "3 cousins in a line: " . factorial(3) . "
"; // 6
echo "Captain + vice from 4: " . arrangements(4, 2) . "
"; // 12
echo "Team of 2 from 4: " . choose(4, 2) . "
"; // 6
echo "Pick 3 of 10: " . choose(10, 3) . "
"; // 120
// List the pairs to prove the count.
$friends = ['A', 'B', 'C', 'D'];
$pairs = [];
for ($i = 0; $i < 4; $i++)
for ($j = $i + 1; $j < 4; $j++) $pairs[] = $friends[$i] . $friends[$j];
echo implode(' ', $pairs) . "
";JavaScript
function factorial(n) {
let f = 1;
for (let i = 2; i <= n; i++) f *= i;
return f;
}
// Arrangements: pick k from n, order matters.
function arrangements(n, k) {
let r = 1;
for (let i = 0; i < k; i++) r *= (n - i);
return r;
}
// Selections: pick k from n, order ignored.
function choose(n, k) {
let r = 1;
for (let i = 1; i <= k; i++) {
r = (r * (n - k + i)) / i; // stays a whole number each step
}
return r;
}
console.log("Thalis: " + (3 * 2 * 4)); // 24
console.log("3 cousins in a line: " + factorial(3)); // 6
console.log("Captain + vice from 4: " + arrangements(4, 2)); // 12
console.log("Team of 2 from 4: " + choose(4, 2)); // 6
console.log("Pick 3 of 10: " + choose(10, 3)); // 120
// List the pairs to prove the count.
const friends = ['A', 'B', 'C', 'D'];
const pairs = [];
for (let i = 0; i < 4; i++)
for (let j = i + 1; j < 4; j++) pairs.push(friends[i] + friends[j]);
console.log(pairs.join(' '));Java
import java.util.*;
public class Main {
static long factorial(int n) {
long f = 1;
for (int i = 2; i <= n; i++) f *= i;
return f;
}
// Arrangements: pick k from n, order matters.
static long arrangements(int n, int k) {
long r = 1;
for (int i = 0; i < k; i++) r *= (n - i);
return r;
}
// Selections: pick k from n, order ignored.
static long choose(int n, int k) {
long r = 1;
for (int i = 1; i <= k; i++) {
r = r * (n - k + i) / i; // stays a whole number each step
}
return r;
}
public static void main(String[] args) {
System.out.println("Thalis: " + (3 * 2 * 4)); // 24
System.out.println("3 cousins in a line: " + factorial(3)); // 6
System.out.println("Captain + vice from 4: " + arrangements(4, 2)); // 12
System.out.println("Team of 2 from 4: " + choose(4, 2)); // 6
System.out.println("Pick 3 of 10: " + choose(10, 3)); // 120
// List the pairs to prove the count.
String[] friends = {"A", "B", "C", "D"};
List<String> pairs = new ArrayList<>();
for (int i = 0; i < 4; i++)
for (int j = i + 1; j < 4; j++) pairs.add(friends[i] + friends[j]);
System.out.println(String.join(" ", pairs));
}
}Go
package main
import (
"fmt"
"strings"
)
func factorial(n int) int {
f := 1
for i := 2; i <= n; i++ {
f *= i
}
return f
}
// arrangements: pick k from n, order matters.
func arrangements(n, k int) int {
r := 1
for i := 0; i < k; i++ {
r *= n - i
}
return r
}
// choose: pick k from n, order ignored.
func choose(n, k int) int {
r := 1
for i := 1; i <= k; i++ {
r = r * (n - k + i) / i // stays a whole number each step
}
return r
}
func main() {
fmt.Println("Thalis:", 3*2*4) // 24
fmt.Println("3 cousins in a line:", factorial(3)) // 6
fmt.Println("Captain + vice from 4:", arrangements(4, 2)) // 12
fmt.Println("Team of 2 from 4:", choose(4, 2)) // 6
fmt.Println("Pick 3 of 10:", choose(10, 3)) // 120
// List the pairs to prove the count.
friends := []string{"A", "B", "C", "D"}
var pairs []string
for i := 0; i < 4; i++ {
for j := i + 1; j < 4; j++ {
pairs = append(pairs, friends[i]+friends[j])
}
}
fmt.Println(strings.Join(pairs, " "))
}Time: O(k) to count a selection · Extra space: O(1). Counting is cheap, but the number of outcomes itself grows astonishingly fast, so never try to list them all for big n.
Watch out for
- Mixing up arrangements and selections. Ask "does swapping two picks change the outcome?"
- Forgetting that factorials explode: 20! already overflows many 64-bit integers.
- Adding choices that should be multiplied (3 + 2 + 4 instead of 3 × 2 × 4).
Quick check
- 3 shirts and 4 trousers. How many outfits?
- 7
- 12
- 24
- In how many ways can 4 friends stand in a line?
- 4
- 16
- 24
- Choose a team of 2 from 4 friends (order ignored). How many teams?
- 6
- 8
- 12