কম্পিউটার বিজ্ঞান · বই 3 · স্নাতক প্রথম বর্ষ

University Computer Science — Year 1

এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: English।

University Computer Science — Year 1 · স্নাতক প্রথম বর্ষ

14Dynamic Arrays and Amortised Analysis

A Python list grows by one element at a time, millions of times, and each append takes about the same short time however long the list already is. Yet a list lives in one block of memory, and a block cannot grow in place: when it is full, a larger block must be reserved and every element copied into it, which costs time proportional to the length. Both statements are true. The way out is to make the copies rare, and to count the cost of a long sequence of operations rather than of one: this is amortised analysis, and this chapter builds the growing array on which it works, in C, behind an interface that hides how it is made.

You already know

A C module is a header, which declares what its users may call, and a source file, which defines it; the users include the header only (Chapter 7). malloc reserves a block on the heap and free returns it (Chapter 4). A cost in Θ(1)\Theta(1) is bounded by a constant independent of the input size (Chapter 13).

14.1 Abstract types and implementations

Definition 14.1 (Abstract data type)

An abstract data type is a type given by a set of operations and their specification, without saying how its values are represented. Its interface is the list of the operations with their signatures; an implementation chooses a representation and writes the operations. Code that uses only the interface works unchanged with any implementation that meets the specification.

Definition 14.2 (Constructor, accessor, transformer)

The operations of an abstract type are of three kinds: a constructor creates a value of the type, an accessor returns information about a value without changing it, and a transformer changes it.

// vec.h: the interface of the abstract type "dynamic array of int".
#ifndef VEC_H
#define VEC_H
#include <stddef.h>

typedef struct vec vec;               // opaque: the fields stay in the implementation

vec *vec_new(void);                   // constructor: an empty array
void vec_free(vec *v);
size_t vec_size(const vec *v);        // accessors
int vec_get(const vec *v, size_t i);  // precondition: i < size
void vec_set(vec *v, size_t i, int x);  // transformers; precondition: i < size
void vec_push(vec *v, int x);         // add x at the end
int vec_pop(vec *v);                  // remove and return the last; precondition: size > 0
size_t vec_capacity(const vec *v);    // for the experiments: cells reserved
long vec_copies(const vec *v);        // for the experiments: elements copied so far
#endif
Listing 14.1. The interface of the dynamic array code/bachelor-1/14-dynamic-arrays/listings/vec.h

The declaration typedef struct vec vec; names a structure without giving its fields: a user can hold a vec * and pass it to the functions, but cannot read or change the fields, which are defined only in the implementation. The compiler enforces the interface. Two files implement it: vec.c, the growing array of this chapter, and fixed.c, an array of 16 cells that refuses a seventeenth element.

An abstract type: the user depends on the interface only, and either implementation can be linked behind it. The fields of struct vec differ between the two files.
An abstract type: the user depends on the interface only, and either implementation can be linked behind it. The fields of struct vec differ between the two files.
$ gcc -std=c17 -O2 -Wall -Wextra vec_demo.c vec.c -o demo_vec
$ gcc -std=c17 -O2 -Wall -Wextra vec_demo.c fixed.c -o demo_fixed
$ ./demo_vec | sed -n '15,18p'
push 15: size 15  capacity 16  copies so far 15
push 16: size 16  capacity 16  copies so far 15
push 17: size 17  capacity 32  copies so far 31
sum of the elements: 153
$ ./demo_fixed 2>&1 | sed -n '15,18p'
push 15: size 15  capacity 16  copies so far  0
push 16: size 16  capacity 16  copies so far  0
vec: full at 16 elements
Output 14.1. The same demonstration linked with each implementation: the fixed one stops at its capacity.

14.2 The doubling array

Definition 14.3 (Dynamic array, size and capacity)

A dynamic array stores a sequence in a block of memory larger than needed. Its size is the number of elements, its capacity the number of cells in the block. Adding an element to a full array first moves the elements to a larger block, whose capacity is a constant factor larger.

Definition 14.4 (Representation invariant)

A representation invariant is a condition on the fields of an implementation that every operation may assume on entry and must restore before returning. It says which values of the fields represent a value of the abstract type.

struct vec {
    int *data;
    size_t size, capacity;
    long copies;
};
// representation invariant: 1 <= capacity, size <= capacity, data holds capacity
// cells, and size > capacity / 4 unless capacity == 1 or the array was just made

static void resize(vec *v, size_t capacity) {
    int *data = malloc(capacity * sizeof *data);
    if (data == NULL) {
        perror("vec");
        exit(1);
    }
    for (size_t i = 0; i < v->size; i++) data[i] = v->data[i];
    v->copies += (long)v->size;
    free(v->data);
    v->data = data;
    v->capacity = capacity;
}
void vec_push(vec *v, int x) {
    if (v->size == v->capacity) resize(v, 2 * v->capacity);
    v->data[v->size++] = x;
}

int vec_pop(vec *v) {
    int x = v->data[--v->size];
    if (v->capacity > 1 && v->size <= v->capacity / 4) resize(v, v->capacity / 2);
    return x;
}
Listing 14.2. The doubling array: the representation, the resize, and the two operations that change the size code/bachelor-1/14-dynamic-arrays/listings/vec.c

The capacity doubles when a push finds the array full, and halves when a pop leaves it a quarter full. Shrinking at a half would be a mistake (Section 14.3). The function resize copies every element and counts the copies, so that the experiments can report them.

$ gcc -std=c17 -O2 -Wall -Wextra -o vec_demo vec_demo.c vec.c -lm && ./vec_demo
push  1: size  1  capacity  1  copies so far  0
push  2: size  2  capacity  2  copies so far  1
push  3: size  3  capacity  4  copies so far  3
push  4: size  4  capacity  4  copies so far  3
push  7: size  7  capacity  8  copies so far  7
push  8: size  8  capacity  8  copies so far  7
push  9: size  9  capacity 16  copies so far 15
push 15: size 15  capacity 16  copies so far 15
push 16: size 16  capacity 16  copies so far 15
push 17: size 17  capacity 32  copies so far 31
sum of the elements: 153
pop   9: size  8  capacity 16  copies so far 39
pop   5: size  4  capacity  8  copies so far 43
pop   3: size  2  capacity  4  copies so far 45
pop   2: size  1  capacity  2  copies so far 46
pop   1: size  0  capacity  1  copies so far 46
Output 14.2. Seventeen pushes, then the pops that shrink the array. Some lines are left out.

14.3 Amortised cost

A push usually costs one write; the push that finds the array full costs one write plus as many copies as there are elements. The worst case of one push is therefore Θ(n)\Theta(n), which is true and misleading: such pushes are rare.

Definition 14.5 (Amortised cost)

Operations on a data structure have amortised cost aa if every sequence of mm operations, starting from the empty structure, costs at most a⋅ma \cdot m in total. The bound concerns the worst sequence, not an average over inputs: no probability is involved.

Definition 14.6 (Aggregate, accounting and potential methods)

Three methods prove amortised bounds. The aggregate method bounds the total cost of any sequence directly. The accounting method charges each operation a fixed number of credits, spends one credit per unit of actual cost, and shows that the credits stored never become negative. The potential method chooses a potential function Φ\Phi from the states of the structure to the reals, and calls ci+Φi−Φi−1c_i + \Phi_i - \Phi_{i-1} the amortised cost of the ii-th operation, of actual cost cic_i; if Φm≥Φ0\Phi_m \geq \Phi_0 after every sequence, the total actual cost is at most the total amortised cost.

The last claim is a telescoping sum: ∑i(ci+Φi−Φi−1)=∑ici+Φm−Φ0≥∑ici\sum_i (c_i + \Phi_i - \Phi_{i-1}) = \sum_i c_i + \Phi_m - \Phi_0 \geq \sum_i c_i.

Proposition 14.7 (Pushes on the doubling array)

Starting from an empty array of capacity 1, nn pushes make fewer than 2n2n copies, and cost fewer than 3n3n writes and copies in all: a push has amortised cost 3.

Proof. Aggregate: the copies happen when the size reaches 1,2,4,…,2j1, 2, 4, \dots, 2^j with 2j<n2^j < n, and copy that many elements: 1+2+⋯+2j=2j+1−1<2n1 + 2 + \dots + 2^j = 2^{j+1} - 1 < 2n. With the nn writes, the total is below 3n3n.

Accounting: charge 3 credits per push. One pays its write; two are stored with the new element. When an array of capacity cc fills up, the c/2c/2 elements pushed since the last resize have stored cc credits, which pay for the cc copies. The store never goes negative.

Potential: let Φ=2⋅size−capacity\Phi = 2 \cdot \text{size} - \text{capacity}, which is −1-1 for the empty array and at least 0 after any push. A push without resize costs 1 and raises Φ\Phi by 2: amortised 3. A push on a full array of size ss costs 1+s1 + s, and Φ\Phi goes from 2s−s=s2s - s = s to 2(s+1)−2s=22(s + 1) - 2s = 2: amortised 1+s+2−s=31 + s + 2 - s = 3. ∎

Seventeen pushes on the doubling array, from . The capacity doubles at pushes 2, 3, 5, 9 and 17, where a push costs one write and as many copies as there are elements; every other push costs 1. The spikes double, but so does the gap between them.
Seventeen pushes on the doubling array, from Output 14.2. The capacity doubles at pushes 2, 3, 5, 9 and 17, where a push costs one write and as many copies as there are elements; every other push costs 1. The spikes double, but so does the gap between them.
The potential = 2 size - capacity along the same pushes: it rises by 2 at each cheap push, storing credit, and falls to 2 at each resize, spending it on the copies. The first dot is the empty array, = -1.
The potential Φ=2⋅size−capacity\Phi = 2 \cdot \text{size} - \text{capacity} along the same pushes: it rises by 2 at each cheap push, storing credit, and falls to 2 at each resize, spending it on the copies. The first dot is the empty array, Φ=−1\Phi = -1.

The same analysis applies to any growth factor r>1r > 1, with r/(r−1)r/(r - 1) copies per push in place of 2 (Exercise 14.10); but not to a growth by a constant number of cells, which makes the copies quadratic. C++’s std::vector specifies push_back as amortised constant time, which rules out a constant increment.

$ gcc -std=c17 -O2 -Wall -Wextra -o copies copies.c -lm && ./copies
        n x1.5: copies, per push   x2: copies, per push  +16: copies, per push
     1000           2104    2.10           1023    1.02          31311   31.31
    10000          24239    2.42          16383    1.64        3120625  312.06
   100000         276464    2.76         131071    1.31      312456250 3124.56
  1000000        2099686    2.10        1048575    1.05    31249562500 31249.56
Output 14.3. Element copies for nn pushes, and per push, for growth by 1.5, by 2 and by 16 cells.
$ gcc -std=c17 -O2 -Wall -Wextra -o timing timing.c -lm && ./timing
       n       x1.5         x2        +16   (ns per push)
    4096       0.54       0.41       5.58
   16384       0.49       0.38      34.08
   65536       2.69       0.31     149.83
  262144       2.70       0.37     817.84
Output 14.4. The same three policies timed on the author’s laptop (best of three, nanoseconds per push).

Copies per push oscillate with nn (they depend on where nn falls between two resizes) but stay below 2 for doubling and below 3 for the factor 1.5, as the bound says; with 16 more cells each time, they grow like n/32n/32. The times agree: doubling costs under half a nanosecond per push and the factor 1.5 from half a nanosecond to under three, while the increment costs four to six times more at each fourfold increase of nn, as copies growing like n/32n/32 predict.

The binary counter is the second classic example. A counter of KK bits is incremented by turning its trailing 1s into 0s and the next 0 into a 1. An increment can flip all KK bits, but bit 0 flips at every increment, bit 1 at every second, bit jj at every 2j2^j-th: nn increments make fewer than n(1+12+14+⋯ )=2nn(1 + \frac12 + \frac14 + \cdots) = 2n flips (Exercises 14.8 and 14.9).

static int increment(int bits[K]) {  // returns the number of bits flipped
    int i = 0;
    while (i < K && bits[i] == 1) bits[i++] = 0;  // the trailing 1s become 0
    if (i < K) bits[i] = 1;                         // and the next 0 becomes 1
    return i < K ? i + 1 : i;
}
Listing 14.3. An increment, counting the flipped bits code/bachelor-1/14-dynamic-arrays/listings/counter.c
$ gcc -std=c17 -O2 -Wall -Wextra -o counter counter.c -lm && ./counter
      n        flips  per incr.
      8           15     1.8750
     64          127     1.9844
    512         1023     1.9980
   4096         8191     1.9998
  32768        65535     2.0000
Output 14.5. Total flips for nn increments from zero. Some lines are left out.

Shrinking

An array that only grows wastes memory after many pops. Halving the capacity when the array is half full looks symmetric with doubling, and is a trap: at a size just above a power of 2, a push doubles the capacity, a pop halves it, and each copies every element. Shrinking at a quarter leaves room in both directions after each resize.

$ gcc -std=c17 -O2 -Wall -Wextra -o thrash thrash.c -lm && ./thrash
shrink at 1/2: 1000 operations after the fill, 1024000 copies, 1024.0 each
shrink at 1/4: 1000 operations after the fill, 1024 copies, 1.0 each
Output 14.6. After filling to 1024 elements, 1000 alternating pushes and pops under each shrinking policy.

14.4 The circular buffer

A queue takes elements at the front and adds them at the back. In an array, taking the front would shift every element, or leave the used part drifting to the right; a circular buffer lets it wrap around.

Definition 14.8 (Circular buffer)

A circular buffer stores a queue in an array of capacity cc with a head index hh and a count kk: the queue is a[h],a[(h+1) mod c],…,a[(h+k−1) mod c]a[h], a[(h + 1) \bmod c], \dots, a[(h + k - 1) \bmod c]. Taking the front advances hh modulo cc; adding at the back writes a[(h+k) mod c]a[(h + k) \bmod c].

void ring_put(ring *r, int x) {
    if (r->count == r->capacity) {  // full: copy in queue order into twice the room
        int *data = checked(calloc(2 * r->capacity, sizeof(int)));
        for (size_t i = 0; i < r->count; i++)
            data[i] = r->data[(r->head + i) % r->capacity];
        free(r->data);
        *r = (ring){data, 0, r->count, 2 * r->capacity};
    }
    r->data[(r->head + r->count) % r->capacity] = x;
    r->count++;
}

int ring_take(ring *r) {
    int x = r->data[r->head];
    r->head = (r->head + 1) % r->capacity;
    r->count--;
    return x;
}
Listing 14.4. Adding and taking, with growth when full code/bachelor-1/14-dynamic-arrays/listings/ring.c
$ gcc -std=c17 -O2 -Wall -Wextra -o ring_demo ring_demo.c ring.c -lm && ./ring_demo
put 1..4     [ 1]  2   3   4   .    size 4
take 1, 2     .   . [ 3]  4   .    size 2
put 5, 6       6   . [ 3]  4   5    size 4
put 7          6   7 [ 3]  4   5    size 5
put 8 (grow) [ 3]  4   5   6   7   8   .   .   .   .    size 6
Output 14.7. A queue in five cells: the front, in brackets, moves right, the back wraps to the start, and the eighth element makes it grow.
A circular buffer before and after it grows. On the left, the queue 3, 4, 5, 6 has wrapped: it starts at index 2 and continues at index 0. Growing copies the queue in order to the start of a larger array.
A circular buffer before and after it grows. On the left, the queue 3, 4, 5, 6 has wrapped: it starts at index 2 and continues at index 0. Growing copies the queue in order to the start of a larger array.

Keeping the count rather than a second index matters: with a head and a tail index only, the full and the empty buffer both have h=th = t (Exercise 14.5). Growth copies the elements in queue order, from the head, not in the order of the cells: copying the cells as they are would break the wrap-around.

In practice

Python’s list and C++’s std::vector are dynamic arrays. Python’s collections.deque is a chain of fixed-size blocks, and the buffers between a producer and a consumer, from keyboard input to network cards, are queues in fixed blocks with wrapping indices. A program that knows how many elements it will push can reserve the capacity once and avoid every copy.

14.5 Exercises

Exercise 14.1 ★

Predict the three lines this program prints, with the doubling array of Listing 14.2.

int main(void) {
    vec *v = vec_new();
    for (int i = 0; i < 6; i++) vec_push(v, i);
    printf("%zu %zu\n", vec_size(v), vec_capacity(v));
    for (int i = 0; i < 4; i++) vec_pop(v);
    printf("%zu %zu\n", vec_size(v), vec_capacity(v));
    vec_push(v, 9);
    vec_push(v, 9);
    vec_push(v, 9);
    printf("%zu %zu %ld\n", vec_size(v), vec_capacity(v), vec_copies(v));
    vec_free(v);
    return 0;
}
Listing 14.5. Pushes and pops code/bachelor-1/14-dynamic-arrays/listings/exo_ops.c
Solution

Solution of Exercise 14.1.

6 8
2 4
5 8 13
Output 14.11. The three lines. Some lines are left out.

Six pushes leave size 6 in capacity 8, after copies 1+2+4=71 + 2 + 4 = 7. The pops bring the size to 5, 4, 3, 2; at 2, 2≤8/42 \leq 8/4, and the capacity halves to 4 with 2 copies. Three pushes: sizes 3 and 4 fit, the fifth element doubles the capacity to 8 with 4 copies: 7+2+4=137 + 2 + 4 = 13.

Exercise 14.2 ★

How many element copies do 10 pushes make on the doubling array, starting from capacity 1? And 10 pushes when each resize adds 2 cells?

Solution

Solution of Exercise 14.2.

Doubling: resizes at pushes 2, 3, 5 and 9, copying 1+2+4+8=151 + 2 + 4 + 8 = 15 elements. Adding 2 cells: capacities 1, 3, 5, 7, 9, 11, with resizes when the size is 1, 3, 5, 7 and 9: 1+3+5+7+9=251 + 3 + 5 + 7 + 9 = 25 copies, already more, and growing quadratically.

Exercise 14.3 ★

A circular buffer of capacity 4 starts empty. Draw its cells, head and count after: put 1, put 2, put 3, take, take, put 4, put 5, put 6, take.

Solution

Solution of Exercise 14.3.

After three puts: [1 2 3 .], h=0h = 0, k=3k = 3. After two takes: h=2h = 2, k=1k = 1 (the queue is 3). Put 4 goes to cell 3, put 5 to cell (2+2) mod 4=0(2 + 2) \bmod 4 = 0, put 6 to cell 1: [5 6 3 4], h=2h = 2, k=4k = 4, full. The last take returns 3: h=3h = 3, k=3k = 3, the queue is 4, 5, 6.

Exercise 14.4 ★

How many bits do 8 increments flip, starting from 0? List the flips of each increment.

Solution

Solution of Exercise 14.4.

The increments from 0 to 8 flip 1, 2, 1, 3, 1, 2, 1 and 4 bits: 15 in all, 2⋅8−12 \cdot 8 - 1.

Exercise 14.5 ★★

This buffer keeps a head and a tail index. Explain the output, and give two ways to repair it.

enum { N = 4 };
int data[N];
int head = 0, tail = 0;  // the queue is data[head..tail), modulo N

int empty(void) { return head == tail; }
void put(int x) { data[tail] = x; tail = (tail + 1) % N; }
int take(void) { int x = data[head]; head = (head + 1) % N; return x; }

int main(void) {
    for (int x = 1; x <= 4; x++) put(x);
    printf("after four puts, empty() says %d\n", empty());
    int n = 0;
    while (!empty()) n++, take();
    printf("taken: %d elements\n", n);
    return 0;
}
Listing 14.6. Head and tail only code/bachelor-1/14-dynamic-arrays/listings/exo_ring_bug.c
after four puts, empty() says 1
taken: 0 elements
Output 14.8. Four puts, and nothing to take. Some lines are left out.
Solution

Solution of Exercise 14.5.

After four puts in four cells, tail has wrapped to 0, equal to head: the full buffer looks empty, and the loop takes nothing. With two indices modulo NN there are only NN possible differences tail - head for N+1N + 1 possible sizes, 0 to NN. Two repairs: keep the count (as Listing 14.4 does), or never fill the last cell, declaring the buffer full when (tail + 1) % N == head, at the price of one unused cell.

Exercise 14.6 ★★

In Output 14.6, explain the 1024 copies per operation of the half policy, and the one copy per operation of the quarter policy. Give a sequence of mm operations that costs Θ(m2)\Theta(m^2) copies under the half policy.

Solution

Solution of Exercise 14.6.

Half policy: at size 1024 in capacity 1024, a push doubles (1024 copies) to size 1025 in 2048; the pop brings the size to 1024≤2048/21024 \leq 2048/2, and the capacity halves (1024 copies). Every operation copies 1024 elements. Quarter policy: the first push copies 1024; then the size moves between 1024 and 1025 in capacity 2048, far from both 2048 and 512: no other copy, so 1024/1000≈11024/1000 \approx 1 per operation. For Θ(m2)\Theta(m^2): m/2=2km/2 = 2^k pushes, then m/2m/2 alternating operations of 2k=m/22^k = m/2 copies each.

Exercise 14.7 ★★

Write an abstract type “stack of int” (stack.h, stack.c) on top of vec.h, with a constructor, two accessors (stack_empty, stack_top) and two transformers, and test it, including on a bracket checker.

Solution

Solution of Exercise 14.7.

struct stack {
    vec *items;  // the top is the last element
};

stack *stack_new(void) {
    stack *s = malloc(sizeof *s);
    if (s == NULL) exit(1);
    s->items = vec_new();
    return s;
}

void stack_free(stack *s) {
    vec_free(s->items);
    free(s);
}

bool stack_empty(const stack *s) { return vec_size(s->items) == 0; }
int stack_top(const stack *s) { return vec_get(s->items, vec_size(s->items) - 1); }
void stack_push(stack *s, int x) { vec_push(s->items, x); }
int stack_pop(stack *s) { return vec_pop(s->items); }
A stack on the dynamic array code/bachelor-1/14-dynamic-arrays/exercises/stack.c

The header exercises/stack.h declares the six operations with typedef struct stack stack;. The top is the last element of the array, so push and pop are those of the array, with amortised cost O(1)O(1). The test pushes and pops 1000 values and checks brackets: ([()[]]) is balanced, ([)] and (( are not.

Exercise 14.8 ★★

By the aggregate method, prove that nn increments of a binary counter, from 0, flip fewer than 2n2n bits.

Solution

Solution of Exercise 14.8.

Bit jj changes at the increment from xx to x+1x + 1 exactly when 2j2^j divides x+1x + 1, which happens ⌊n/2j⌋\lfloor n/2^j \rfloor times for x+1=1,…,nx + 1 = 1, \dots, n. The total is ∑j≥0⌊n/2j⌋<n∑j2−j=2n\sum_{j \geq 0} \lfloor n/2^j \rfloor < n \sum_j 2^{-j} = 2n.

Exercise 14.9 ★★

Prove the same bound by the accounting method: how many credits per increment, and where are they stored?

Solution

Solution of Exercise 14.9.

Charge 2 credits per increment. An increment sets exactly one bit from 0 to 1 (unless it overflows): one credit pays that flip, and the other is stored on the bit that is now 1. The flips from 1 to 0 are paid by the credits stored on those bits. Every bit at 1 holds one credit, so the store is never negative, and nn increments flip at most 2n2n bits.

Exercise 14.10 ★★★

The array grows by a factor r>1r > 1 when full (capacity cc becomes at least rcrc, for instance ⌈rc⌉\lceil rc \rceil; the factor 1.5 of the programs gives c+⌊c/2⌋+1c + \lfloor c/2 \rfloor + 1). Prove with a potential that nn pushes make at most about rr−1n\frac{r}{r - 1} n copies, and compare with Output 14.3.

Solution

Solution of Exercise 14.10.

Let Φ=αs−c/(r−1)\Phi = \alpha s - c/(r - 1) for size ss and capacity cc. A push without resize copies nothing and raises Φ\Phi by α\alpha. A push on a full array of size s=cs = c copies cc elements, and, the capacity growing by at least (r−1)c(r - 1)c, Φ\Phi changes by at most α−(r−1)c/(r−1)=α−c\alpha - (r - 1)c/(r - 1) = \alpha - c: amortised c+α−c=αc + \alpha - c = \alpha copies. Right after a resize s≥c/rs \geq c/r, so Φ≥c(α/r−1/(r−1))\Phi \geq c(\alpha/r - 1/(r - 1)), which is non-negative for α=r/(r−1)\alpha = r/(r - 1); it stays so as pushes raise it. Hence nn pushes copy at most rr−1n\frac{r}{r - 1} n plus a constant from Φ0\Phi_0 and the rounding of the new capacity. For r=1.5r = 1.5 the bound is 3 (the table reaches 2.76), for r=2r = 2 it is 2 (the table reaches 1.64).

Exercise 14.11 ★★★

With growth ×2\times 2 and shrinking to half when a quarter full, prove that any sequence of mm pushes and pops from the empty array makes at most 2m2m copies. Use Φ=2s−c\Phi = 2s - c when s≥c/2s \geq c/2 and Φ=c/2−s\Phi = c/2 - s when s<c/2s < c/2, for size ss and capacity cc.

Solution

Solution of Exercise 14.11.

Φ≥0\Phi \geq 0 always, and Φ0=12\Phi_0 = \frac12 for the empty array of capacity 1. Pushes: in the upper half, ΔΦ=+2\Delta\Phi = +2; in the lower half, −1-1; on a full array of size cc, cc copies and Φ\Phi goes from cc to 2, amortised 2−c+c=22 - c + c = 2. Pops without resize: −2-2 in the upper half, +1+1 in the lower. A pop that shrinks leaves size c/4c/4 in capacity c/2c/2: Φ\Phi goes from c/2−(c/4+1)=c/4−1c/2 - (c/4 + 1) = c/4 - 1 to 2⋅c/4−c/2=02 \cdot c/4 - c/2 = 0, with c/4c/4 copies: amortised 1 (the small capacities 4 and 2 give 1 and 12\frac12). Every amortised cost is at most 2, so mm operations copy at most 2m+Φ0−Φm≤2m+122m + \Phi_0 - \Phi_m \leq 2m + \frac12, hence at most 2m2m, an integer. The test checks it along 200 000 random operations.

Exercise 14.12 ★★★

Write a dynamic array of elements of any type: the constructor takes the size of an element in bytes, push copies an element from an address, and gvec_at returns the address of an element. Test it with double and with a structure.

Solution

Solution of Exercise 14.12.

struct gvec {
    unsigned char *data;
    size_t elem_size, size, capacity;
};

static void resize(gvec *v, size_t capacity) {
    unsigned char *data = malloc(capacity * v->elem_size);
    if (data == NULL) exit(1);
    if (v->size > 0) memcpy(data, v->data, v->size * v->elem_size);
    free(v->data);
    v->data = data;
    v->capacity = capacity;
}
size_t gvec_size(const gvec *v) { return v->size; }
void *gvec_at(gvec *v, size_t i) { return v->data + i * v->elem_size; }

void gvec_push(gvec *v, const void *elem) {
    if (v->size == v->capacity) resize(v, 2 * v->capacity);
    memcpy(gvec_at(v, v->size++), elem, v->elem_size);
}

void gvec_pop(gvec *v, void *out) {
    memcpy(out, gvec_at(v, --v->size), v->elem_size);
    if (v->capacity > 1 && v->size <= v->capacity / 4) resize(v, v->capacity / 2);
}
The generic array: bytes and an element size code/bachelor-1/14-dynamic-arrays/exercises/gvec.c

Elements are copied with memcpy, elem_size bytes at a time, and the address of element ii is the start of the block plus i⋅elem_sizei \cdot \text{elem\_size}. The user casts it back: *(double *)gvec_at(d, 4000). The test pushes 5000 doubles and pops them back in reverse, then stores three book structures and changes one in place through its address.

14.6 Problem: The binary counter and the elastic array

Problem 14.1

Weekend problem — The binary counter and the elastic array

A program tries every sequence of mm pushes and pops on the policy of vec.c (double when full, halve when a quarter full), for even mm up to 26, and prints the largest number of copies with one sequence that makes them.

static long copies_of(long m, long mask) {  // bit i of mask: 1 push, 0 pop
    long size = 0, capacity = 1, copies = 0;
    for (long i = 0; i < m; i++) {
        if (mask >> i & 1) {
            if (size == capacity) {
                copies += size;
                capacity *= 2;
            }
            size++;
        } else {
            if (size == 0) return -1;  // a pop on the empty array: not allowed
            size--;
            if (capacity > 1 && size <= capacity / 4) {
                copies += size;
                capacity /= 2;
            }
        }
    }
    return copies;
}
Listing 14.7. Copies of one sequence of operations code/bachelor-1/14-dynamic-arrays/listings/elastic.c
$ gcc -std=c17 -O2 -Wall -Wextra -o elastic elastic.c -lm && ./elastic
 m copies  copies/m  a worst sequence (+ push, - pop)
 2      1     0.500  ++
 4      3     0.750  +++-
 6      7     1.167  +++++-
 8      9     1.125  +++++---
10     15     1.500  +++++++++-
12     15     1.250  +++++++++---
14     19     1.357  +++++++++-----
16     21     1.312  +++++++++-------
18     31     1.722  +++++++++++++++++-
20     31     1.550  +++++++++++++++++---
22     34     1.545  +++--++++++++++++++++-
24     37     1.542  +++++---+++++++++++++++-
26     40     1.538  +++++----++++++++++++++++-
Output 14.9. The worst sequences found.
from 2^15 - 1, 1000 increments and decrements alternating: 16000 flips, 16.0 each
Output 14.10. The counter of Listing 14.3, with a decrement, alternating around 2152^{15}. Some lines are left out.

Part I — The counter.

  1. Show that an increment from xx flips t+1t + 1 bits, where tt is the number of trailing 1s of xx (when t<Kt < K).
  2. How many of the integers 0≤x<2K0 \leq x < 2^K have exactly tt trailing 1s?
  3. Show that bit jj flips exactly ⌊n/2j⌋\lfloor n/2^j \rfloor times in nn increments from 0.
  4. Deduce that the total is ∑j⌊n/2j⌋<2n\sum_j \lfloor n/2^j \rfloor < 2n, and that it equals 2n−12n - 1 when nn is a power of 2.
  5. Check the table of Output 14.5.
  6. What is the worst case of a single increment, and why does it not contradict the amortised bound?

Part II — The doubling array, three ways.

  1. Count exactly the copies made by nn pushes from capacity 1, as a function of nn.
  2. Write the accounting argument for pushes with 3 credits each, and say why 2 credits would not do.
  3. Check that Φ=2⋅size−capacity\Phi = 2 \cdot \text{size} - \text{capacity} is at least 0 after every push.
  4. Give the amortised cost of each push of Output 14.2 with this Φ\Phi.
  5. With nn pushes, what is the largest capacity, and so the largest unused memory, as a fraction of the size?
  6. Which of the three methods would you use to explain the result to a colleague, and why?

Part III — Shrinking.

  1. With shrinking at a half, describe the state after filling to 2k2^k elements, then one push, then one pop.
  2. Deduce that mm alternating operations after the fill cost Θ(m⋅2k)\Theta(m \cdot 2^k) copies.
  3. With shrinking at a quarter, show that after any resize the size is exactly half the new capacity.
  4. Deduce that between two resizes at least a quarter of the capacity’s worth of operations happen.
  5. Read the table of Output 14.9: which sequences are the worst, and what is the largest ratio of copies to operations?
  6. Show that 2k+12^k + 1 pushes make 2k+1−12^{k+1} - 1 copies, so that the ratio approaches 2.

Part IV — A decrement breaks the bound.

  1. Write the decrement of the counter, and give the flips of a decrement from 2j2^j.
  2. From 215−12^{15} - 1, alternate increment and decrement: how many flips per operation? Check with Output 14.10.
  3. Deduce that nn operations among increments and decrements can cost Θ(nlog⁡n)\Theta(n \log n) flips when the counter has log⁡2n\log_2 n bits.
  4. With digits −1-1, 0 and 1 in base 2 (each number then has several representations), an increment and a decrement can each be made to change a bounded number of digits in the amortised sense. Why does this not contradict the previous question?
  5. Is the amortised bound of the array, 2m2m copies, still valid for any mix of pushes and pops? Why do pops not break it as decrements break the counter’s?
  6. State the named result of the problem, the elastic array theorem: the constant cc with at most c⋅mc \cdot m copies for any mm operations, why it is the smallest, and the worst ratios found by the program.
Solution

Solution of Problem 14.1.

1. The tt trailing 1s become 0 and the next bit, a 0, becomes 1: t+1t + 1 flips.

2. Bits 0 to t−1t - 1 are 1, bit tt is 0, the K−t−1K - t - 1 others are free: 2K−t−12^{K - t - 1} integers.

3. Bit jj flips from xx to x+1x + 1 exactly when 2j2^j divides x+1x + 1: ⌊n/2j⌋\lfloor n/2^j \rfloor times.

4. ∑j⌊n/2j⌋<n∑j2−j=2n\sum_j \lfloor n/2^j \rfloor < n \sum_j 2^{-j} = 2n; for n=2kn = 2^k the sum is 2k+2k−1+⋯+1=2k+1−12^k + 2^{k-1} + \dots + 1 = 2^{k+1} - 1.

5. 15, 127, 1023, 8191 and 65 535 flips for n=8,64,512,4096,32 768n = 8, 64, 512, 4096, 32\,768: each is 2n−12n - 1.

6. From 2K−12^K - 1, all KK bits flip. Such increments are rare: one in 2K2^{K} from 0.

7. 2⌈log⁡2n⌉−12^{\lceil \log_2 n \rceil} - 1: the resizes copy 1,2,…,2j1, 2, \dots, 2^j with 2j<n2^j < n. For n=17n = 17, 31.

8. A push pays its write and stores two credits on its element. When capacity cc fills, the c/2c/2 elements pushed since the last resize hold cc credits, one per copy. With 2 credits, only c/2c/2 would be stored.

9. After a push the array holds more than half its capacity: either no resize happened and the size grew, or a resize left size c+1c + 1 in capacity 2c2c. So 2s−c>02s - c > 0.

10. 3 for each of the seventeen pushes, as the dashed line of the figure shows.

11. The capacity is 2⌈log⁡2n⌉<2n2^{\lceil \log_2 n \rceil} < 2n: the unused cells are fewer than the elements, nearly as many right after a resize.

12. The accounting method: credits stored on elements show where the cost of a copy comes from.

13. Size 2k2^k in capacity 2k2^k; the push copies 2k2^k elements into capacity 2k+12^{k+1}; the pop leaves size 2k2^k, half of it, and copies 2k2^k elements back into capacity 2k2^k. The state is the same as after the fill.

14. Each operation then copies 2k2^k elements: m⋅2km \cdot 2^k copies.

15. A growth copies cc elements into capacity 2c2c; a shrink copies c/4c/4 elements into capacity c/2c/2. Either way the copied elements fill exactly half the new capacity CC.

16. The next growth needs C/2C/2 more pushes, the next shrink at least C/4C/4 pops; a resize copies at most CC elements, so the copies are paid by at least C/4C/4 operations: a first, crude bound of 4 per operation.

17. The worst sequences push up to just past a power of 2, sometimes after a shrink and a regrowth (+++--+++…). The largest ratio is 31/18≈1.72231/18 \approx 1.722, at m=18m = 18: seventeen pushes and one pop.

18. The resizes copy 1+2+⋯+2k=2k+1−11 + 2 + \dots + 2^k = 2^{k+1} - 1 elements, and 2k+1−12k+1→2\frac{2^{k+1} - 1}{2^k + 1} \to 2.

19. The trailing 0s become 1 and the next 1 becomes 0. From 2j2^j: j+1j + 1 flips.

20. 16 per operation: from 215−12^{15} - 1 (fifteen 1s), the increment flips 16 bits to reach 2152^{15}, the decrement flips them back. The output shows 16 000 flips for 1000 operations.

21. Each operation flips log⁡2n+1\log_2 n + 1 bits when the counter alternates between 2k−12^k - 1 and 2k2^k with 2k≈n2^k \approx n: Θ(nlog⁡n)\Theta(n \log n) in all.

22. Question 21 is about the standard representation, which is unique: 2k−12^k - 1 and 2k2^k differ in k+1k + 1 bits, so any method that stores them must flip them. A redundant representation does not store either, but some equivalent form of each, which leaves room to absorb a carry later.

23. Yes: the potential of Exercise 14.11 covers any mix. The quarter rule leaves slack in both directions after each resize; the binary counter has no slack between 2k−12^k - 1 and 2k2^k.

24. The elastic array theorem: with growth ×2\times 2 and shrinking to half when a quarter full, any mm pushes and pops from the empty array make at most 2m2m element copies (Exercise 14.11). The constant 2 is the smallest possible: 2k+12^k + 1 pushes make 2k+1−12^{k+1} - 1 copies, a ratio that approaches 2. The exhaustive search finds at most 1.722 copies per operation for m≤26m \leq 26, at seventeen pushes and a pop.

এই অধ্যায়ে সংজ্ঞায়িত পরিভাষা-শব্দ

পরিভাষায় সব 1050 টি শব্দ দেখো