Test iOS task assignment with maximum matching

Test iOS task assignment with maximum matching

Test iOS task assignment with maximum matching

When a development studio delivers booking, scheduling, or equipment checkout features for a client, a common constraint is that each task can use only one resource, and each resource can serve only one task. Picking the first available resource in list order may look reasonable in the interface, yet leave more tasks unassigned than necessary. Extracting the assignment logic into a pure Swift function lets you validate the algorithm on a cloud Mac before connecting it to the iOS interface and persistence layer.

Define a maximum-cardinality assignment contract

Place tasks on the left side of a bipartite graph and resources on the right. Each task has an edge to every resource it is allowed to use. For example, task A can use resources zero and one, while task B can use only resource zero. Giving zero to A first leaves B unassigned. The correct approach is to move A to one so that B can take zero.

This article optimizes only the number of assigned tasks—not cost, priority, or waiting time. Every resource has a capacity of one; a pool with multiple places cannot simply be represented as a single resource node.

“There is no free resource available directly” does not mean “the number of assignments cannot increase.” Existing matches can be rearranged along an augmenting path.

The result must satisfy three conditions: each task appears at most once, each resource is used at most once, and every pair is an allowed input edge. A valid result can still fail the contract if its cardinality is not maximum.

Implement augmenting paths that can rearrange assignments

The function below returns the task index assigned to each resource index, with nil for unassigned resources. Save it as Matching.swift and append the verification code later in this article to the same file. Candidate indices outside the resource range cause an error rather than being silently ignored.

enum MatchingError: Error {
    case invalidResource
}

func maximumMatching(
    _ choices: [[Int]],
    resourceCount: Int
) throws -> [Int?] {
    guard resourceCount >= 0,
          choices.allSatisfy({
              $0.allSatisfy { $0 >= 0 && $0 < resourceCount }
          }) else {
        throw MatchingError.invalidResource
    }

    var owner = [Int?](repeating: nil, count: resourceCount)

    func augment(_ task: Int, _ seen: inout [Bool]) -> Bool {
        for resource in choices[task] {
            if seen[resource] { continue }
            seen[resource] = true

            if let previous = owner[resource] {
                if !augment(previous, &seen) { continue }
            }

            owner[resource] = task
            return true
        }
        return false
    }

    for task in choices.indices {
        var seen = [Bool](repeating: false, count: resourceCount)
        _ = augment(task, &seen)
    }
    return owner
}

Each search starts from a new task, so the visited flags must be reset for every iteration. When the search encounters an occupied resource, it recursively tries to move the current owner elsewhere. Ownership is updated only when the entire path succeeds. A failed branch leaves no partially completed reassignment behind.

Each iteration also initializes the resource-visited array. If the numbers of tasks, resources, and candidate edges are T, R, and E respectively, the overall time bound is O(T × (R + E)). Recursion depth grows with the length of the alternating path. For large, untrusted inputs, impose limits on the numbers of tasks, resources, and candidate edges rather than accepting unbounded input.

Establish a cardinality oracle with independent exhaustive search

Testing only a few handwritten answers can easily miss graphs that require several consecutive reassignments. Build a separate reference solver that does not use augmenting paths: for each task, enumerate leaving it unassigned and assigning it to each available candidate, then return the largest number of assignments.

func oracle(_ choices: [[Int]], resourceCount: Int) -> Int {
    var used = [Bool](repeating: false, count: resourceCount)

    func search(_ task: Int) -> Int {
        if task == choices.count { return 0 }
        var best = search(task + 1)

        for resource in choices[task] where !used[resource] {
            used[resource] = true
            best = max(best, 1 + search(task + 1))
            used[resource] = false
        }
        return best
    }
    return search(0)
}

func verify(_ choices: [[Int]], resourceCount: Int) throws {
    let result = try maximumMatching(
        choices, resourceCount: resourceCount
    )
    var tasks = Set<Int>()

    for (resource, task) in result.enumerated() {
        guard let task else { continue }
        precondition(choices.indices.contains(task))
        precondition(choices[task].contains(resource))
        precondition(tasks.insert(task).inserted)
    }

    precondition(
        tasks.count == oracle(choices, resourceCount: resourceCount)
    )
}

for mask in 0..<(1 << 9) {
    var choices = [[Int]](repeating: [], count: 3)
    for task in 0..<3 {
        for resource in 0..<3 {
            if mask & (1 << (task * 3 + resource)) != 0 {
                choices[task].append(resource)
            }
        }
    }
    try verify(choices, resourceCount: 3)
}

Three tasks and three resources have nine possible edges, so this checks all five hundred and twelve graphs. The reference solver has exponential growth and belongs only in small-scale tests, not in the production assignment path. Validity is checked before cardinality so that a result cannot pass merely by reaching the expected count while reusing the same task.

Cover empty inputs and non-unique solutions

Append the following boundary cases, then run the file. Using precondition keeps the checks active in normal optimized builds; do not use an unsafe optimization configuration that removes them.

try verify([], resourceCount: 0)
try verify([[], []], resourceCount: 0)
try verify([[0, 0], [0]], resourceCount: 1)
try verify([[0, 1], [0]], resourceCount: 2)
try verify([[0, 1], [0, 1]], resourceCount: 2)

do {
    _ = try maximumMatching([[1]], resourceCount: 1)
    preconditionFailure("Expected invalid resource")
} catch MatchingError.invalidResource {
}
xcrun swift Matching.swift

The script produces no output on success and exits with a nonzero status on failure. Keep it as a separate acceptance step so that a failed check cannot be followed by delivery as though nothing had happened.

When both tasks can use either of two resources, several answers are equally correct. Tests must not require each task to receive a particular resource index every time. Changing candidate order may also change the pairs, but it must not change the maximum cardinality. If the client requires stable presentation, define an explicit tie-breaking rule first. Sorting candidates only fixes the traversal order of the current implementation; it does not automatically guarantee fairness in business terms.

Preserve the decision snapshot during integration

Real interfaces usually work with business identifiers rather than consecutive integers. Build index mappings for the tasks and resources in the current snapshot, then map the result back to identifiers after matching. Reject duplicate identifiers to avoid accidentally merging two records. Do not read from changing UI arrays while the calculation is in progress.

A maximum matching is not the same as a successful booking. If another request can claim a resource after the result is returned, the write side must still check a version or use a transaction. After a conflict, fetch a fresh snapshot and recompute rather than arbitrarily placing only the failed task into another free slot.

Keep the input snapshot, allowed edges, matching cardinality, and algorithm version in the delivery record. Sensitive business identifiers can be replaced with test IDs. First use exhaustive tests on small graphs to establish that the cardinality is correct, then use client examples to confirm that the constraints have been modeled correctly. That is how “the tasks can be assigned” becomes a repeatable engineering acceptance criterion.

Frequently asked questions

Does maximum matching also optimize priorities or cost?

No. This implementation maximizes the number of assigned tasks. Priorities, costs, and fairness require a separate model and an appropriate optimization algorithm.

What should tests compare when several optimal assignments exist?

Verify that all pairs are allowed and neither tasks nor resources repeat, then compare cardinality. Assert exact pairs only when the product specifies a tie-breaking rule.

Add a cloud Mac for your project

Dedicated Apple Silicon M4 physical nodes, available by the day, week, month, or quarter. Your rental stops at the end of the term—no idle machines after your project wraps up.

Choose a rental term

Rent a Mac for your project

Dedicated Apple Silicon M4 physical nodes, available by the day. Your rental stops at the end of the term.