summaryrefslogtreecommitdiffstats
path: root/lab1/lib/StanfordCPPLib/grid.h
blob: 8e74998fbe82f4b06e7fb84915cd1f1ed68e6d68 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
/*
 * File: grid.h
 * ------------
 * This file exports the <code>Grid</code> class, which offers a
 * convenient abstraction for representing a two-dimensional array.
 */

#ifndef _grid_h
#define _grid_h

#include <string>
#include <sstream>
#include <vector>
#include <stdexcept>

/*
 * Class: Grid<ValueType>
 * ----------------------
 * This class stores an indexed, two-dimensional array.  The following code,
 * for example, creates an identity matrix of size <code>n</code>, in which
 * the elements are 1.0 along the main diagonal and 0.0 everywhere else:
 *
 *<pre>
 *    Grid&lt;double&gt; createIdentityMatrix(int n) {
 *       Grid&lt;double&gt; matrix(n, n);
 *       for (int i = 0; i &lt; n; i++) {
 *          matrix[i][i] = 1.0;
 *       }
 *       return matrix;
 *    }
 *</pre>
 */

template <typename ValueType>
class Grid {

public:

    /* Forward reference */
    class GridRow;
    class ConstGridRow;

    /*
 * Constructor: Grid
 * Usage: Grid<ValueType> grid;
 *        Grid<ValueType> grid(nRows, nCols);
 * ------------------------------------------
 * Initializes a new grid.  The second form of the constructor is
 * more common and creates a grid with the specified number of rows
 * and columns.  Each element of the grid is initialized to the
 * default value for the type.  The default constructor creates an
 * empty grid for which the client must call <code>resize</code> to
 * set the dimensions.
 */

    Grid();
    Grid(int nRows, int nCols);

    /*
 * Destructor: ~Grid
 * -----------------
 * Frees any heap storage associated with this grid.
 */

    virtual ~Grid();

    /*
 * Method: numRows
 * Usage: int nRows = grid.numRows();
 * ----------------------------------
 * Returns the number of rows in the grid.
 */

    int numRows() const;

    /*
 * Method: numCols
 * Usage: int nCols = grid.numCols();
 * ----------------------------------
 * Returns the number of columns in the grid.
 */

    int numCols() const;

    /*
 * Method: resize
 * Usage: grid.resize(nRows, nCols);
 * ---------------------------------
 * Reinitializes the grid to have the specified number of rows
 * and columns.  Any previous grid contents are discarded.
 */

    void resize(int nRows, int nCols);

    /*
 * Method: inBounds
 * Usage: if (grid.inBounds(row, col)) ...
 * ---------------------------------------
 * Returns <code>true</code> if the specified row and column position
 * is inside the bounds of the grid.
 */

    bool inBounds(int row, int col) const;

    /*
 * Method: get
 * Usage: ValueType value = grid.get(row, col);
 * --------------------------------------------
 * Returns the element at the specified <code>row</code>/<code>col</code>
 * position in this grid.  This method signals an error if the
 * <code>row</code> and <code>col</code> arguments are outside
 * the grid boundaries.
 */

    ValueType get(int row, int col);
    const ValueType & get(int row, int col) const;

    /*
 * Method: set
 * Usage: grid.set(row, col, value);
 * ---------------------------------
 * Replaces the element at the specified <code>row</code>/<code>col</code>
 * location in this grid with a new value.  This method signals an error
 * if the <code>row</code> and <code>col</code> arguments are outside
 * the grid boundaries.
 */

    void set(int row, int col, ValueType value);

    /*
 * Operator: []
 * Usage:  grid[row][col]
 * ----------------------
 * Overloads <code>[]</code> to select elements from this grid.
 * This extension enables the use of traditional array notation to
 * get or set individual elements.  This method signals an error if
 * the <code>row</code> and <code>col</code> arguments are outside
 * the grid boundaries.
 */

    GridRow operator[](int row);
    const ConstGridRow operator[](int row) const;

    /*
 * Method: toString
 * Usage: string str = grid.toString();
 * ------------------------------------
 * Converts the grid to a printable string representation.
 */

    std::string toString();

    /*
 * Method: mapAll
 * Usage: grid.mapAll(fn);
 * -----------------------
 * Calls the specified function on each element of the grid.  The
 * elements are processed in <b><i>row-major order,</i></b> in which
 * all the elements of row 0 are processed, followed by the elements
 * in row 1, and so on.
 */

    void mapAll(void (*fn)(ValueType value)) const;
    void mapAll(void (*fn)(const ValueType & value)) const;

    template <typename FunctorType>
    void mapAll(FunctorType fn) const;

    /*
 * Additional Grid operations
 * --------------------------
 * In addition to the methods listed in this interface, the Grid
 * class supports the following operations:
 *
 *   - Stream I/O using the << and >> operators
 *   - Deep copying for the copy constructor and assignment operator
 *   - Iteration using the range-based for statement and STL iterators
 *
 * The iteration forms process the grid in row-major order.
 */

    /* Private section */

    /**********************************************************************/
    /* Note: Everything below this point in the file is logically part    */
    /* of the implementation and should not be of interest to clients.    */
    /**********************************************************************/

    /*
 * Implementation notes: Grid data structure
 * -----------------------------------------
 * The Grid is internally managed as a dynamic array of elements.
 * The array itself is one-dimensional, the logical separation into
 * rows and columns is done by arithmetic computation.  The layout
 * is in row-major order, which is to say that the entire first row
 * is laid out contiguously, followed by the entire second row,
 * and so on.
 */

    /* Instance variables */

    ValueType *elements;  /* A dynamic array of the elements   */
    int nRows;            /* The number of rows in the grid    */
    int nCols;            /* The number of columns in the grid */

    /* Private method prototypes */

    void checkRange(int row, int col);

    /*
 * Hidden features
 * ---------------
 * The remainder of this file consists of the code required to
 * support deep copying and iteration.  Including these methods
 * in the public interface would make that interface more
 * difficult to understand for the average client.
 */

    /*
 * Deep copying support
 * --------------------
 * This copy constructor and operator= are defined to make a
 * deep copy, making it possible to pass/return grids by value
 * and assign from one grid to another.  The entire contents of
 * the grid, including all elements, are copied.  Each grid
 * element is copied from the original grid to the copy using
 * assignment (operator=).  Making copies is generally avoided
 * because of the expense and thus, grids are typically passed
 * by reference, however, when a copy is needed, these operations
 * are supported.
 */

    void deepCopy(const Grid & grid) {
        int n = grid.nRows * grid.nCols;
        elements = new ValueType[n];
        for (int i = 0; i < n; i++) {
            elements[i] = grid.elements[i];
        }
        nRows = grid.nRows;
        nCols = grid.nCols;
    }

public:

    Grid & operator=(const Grid & src) {
        if (this != &src) {
            delete[] elements;
            deepCopy(src);
        }
        return *this;
    }

    Grid(const Grid & src) {
        deepCopy(src);
    }

    /*
 * Iterator support
 * ----------------
 * The classes in the StanfordCPPLib collection implement input
 * iterators so that they work symmetrically with respect to the
 * corresponding STL classes.
 */

    class iterator : public std::iterator<std::input_iterator_tag, ValueType> {

    public:

        iterator(const Grid *gp, int index) {
            this->gp = gp;
            this->index = index;
        }

        iterator(const iterator & it) {
            this->gp = it.gp;
            this->index = it.index;
        }

        iterator & operator++() {
            index++;
            return *this;
        }

        iterator operator++(int) {
            iterator copy(*this);
            operator++();
            return copy;
        }

        bool operator==(const iterator & rhs) {
            return gp == rhs.gp && index == rhs.index;
        }

        bool operator!=(const iterator & rhs) {
            return !(*this == rhs);
        }

        ValueType & operator*() {
            return gp->elements[index];
        }

        ValueType *operator->() {
            return &gp->elements[index];
        }

    private:
        const Grid *gp;
        int index;
    };

    iterator begin() const {
        return iterator(this, 0);
    }

    iterator end() const {
        return iterator(this, nRows * nCols);
    }

    /*
 * Private class: Grid<ValType>::GridRow
 * -------------------------------------
 * This section of the code defines a nested class within the Grid template
 * that makes it possible to use traditional subscripting on Grid values.
 */

    class GridRow {
    public:
        GridRow() {
            /* Empty */
        }

        ValueType & operator[](int col) {
            if (!gp->inBounds(row, col)) {
                throw std::out_of_range("Grid index values out of range");
            }
            return gp->elements[(row * gp->nCols) + col];
        }

        ValueType operator[](int col) const {
            if (!gp->inBounds(row, col)) {
                throw std::out_of_range("Grid index values out of range");
            }
            return gp->elements[(row * gp->nCols) + col];
        }

    private:
        GridRow(Grid *gridRef, int index) {
            gp = gridRef;
            row = index;
        }

        Grid *gp;
        int row;
        friend class Grid;
    };
    friend class ConstGridRow;

    /*
 * Private class: Grid<ValType>::ConstGridRow
 * -------------------------------------
 * This section of the code defines a nested class within the Grid template
 * that makes it possible to use traditional subscripting on Grid values for
 * const versions of the Grid.
 */

    class ConstGridRow {
    public:
        ConstGridRow() {
            /* Empty */
        }

        ValueType operator[](int col) const {
            if (!gp->inBounds(row, col)) {
                throw std::out_of_range("Grid index values out of range");
            }
            return gp->elements[(row * gp->nCols) + col];
        }

    private:
        ConstGridRow(const Grid *gridRef, int index) {
            gp = gridRef;
            row = index;
        }

        const Grid *gp;
        int row;
        friend class Grid;
    };
    friend class GridRow;

};

template <typename ValueType>
Grid<ValueType>::Grid() {
    elements = NULL;
    nRows = 0;
    nCols = 0;
}

template <typename ValueType>
Grid<ValueType>::Grid(int nRows, int nCols) {
    elements = NULL;
    resize(nRows, nCols);
}

template <typename ValueType>
Grid<ValueType>::~Grid() {
    if (elements != NULL) delete[] elements;
}

template <typename ValueType>
int Grid<ValueType>::numRows() const {
    return nRows;
}

template <typename ValueType>
int Grid<ValueType>::numCols() const {
    return nCols;
}

template <typename ValueType>
void Grid<ValueType>::resize(int nRows, int nCols) {
    if (nRows < 0 || nCols < 0) {
        throw std::invalid_argument("Attempt to resize grid to invalid size ("
                                    + std::to_string(nRows) + ", "
                                    + std::to_string(nCols) + ")");
    }
    if (elements != NULL) delete[] elements;
    this->nRows = nRows;
    this->nCols = nCols;
    elements = new ValueType[nRows * nCols];
    ValueType value = ValueType();
    for (int i = 0; i < nRows * nCols; i++) {
        elements[i] = value;
    }
}

template <typename ValueType>
bool Grid<ValueType>::inBounds(int row, int col) const {
    return row >= 0 && col >= 0 && row < nRows && col < nCols;
}

template <typename ValueType>
ValueType Grid<ValueType>::get(int row, int col) {
    if (!inBounds(row, col)) throw std::out_of_range("get: Grid indices out of bounds");
    return elements[(row * nCols) + col];
}

template <typename ValueType>
const ValueType & Grid<ValueType>::get(int row, int col) const {
    if (!inBounds(row, col)) throw std::out_of_range("get: Grid indices out of bounds");
    return elements[(row * nCols) + col];
}

template <typename ValueType>
void Grid<ValueType>::set(int row, int col, ValueType value) {
    if (!inBounds(row, col)) throw std::out_of_range("set: Grid indices out of bounds");
    elements[(row * nCols) + col] = value;
}

template <typename ValueType>
typename Grid<ValueType>::GridRow Grid<ValueType>::operator[](int row) {
    return GridRow(this, row);
}

template <typename ValueType>
const typename Grid<ValueType>::ConstGridRow
Grid<ValueType>::operator[](int row) const {
    return ConstGridRow(this, row);
}

template <typename ValueType>
void Grid<ValueType>::mapAll(void (*fn)(ValueType value)) const {
    for (int i = 0; i < nRows; i++) {
        for (int j = 0; j < nCols; j++) {
            fn(get(i, j));
        }
    }
}

template <typename ValueType>
void Grid<ValueType>::mapAll(void (*fn)(const ValueType & value)) const {
    for (int i = 0; i < nRows; i++) {
        for (int j = 0; j < nCols; j++) {
            fn(get(i, j));
        }
    }
}

template <typename ValueType>
template <typename FunctorType>
void Grid<ValueType>::mapAll(FunctorType fn) const {
    for (int i = 0; i < nRows; i++) {
        for (int j = 0; j < nCols; j++) {
            fn(get(i, j));
        }
    }
}

template <typename ValueType>
std::string Grid<ValueType>::toString() {
    std::ostringstream os;
    os << *this;
    return os.str();
}


template <typename ValueType>
std::ostream & operator<<(std::ostream & os, const Grid<ValueType> & grid) {
    os << "{";
    int nRows = grid.numRows();
    int nCols = grid.numCols();
    for (int i = 0; i < nRows; i++) {
        if (i > 0) os << ", ";
        os << "{";
        for (int j = 0; j < nCols; j++) {
	  if (j > 0)
	    os << ", ";
	  os << grid.get(i,j);
        }
        os << "}";
    }
    return os << "}";
}


#endif