#include "TileList.h" TileList::TileList() { tiles = new Tile[INITIAL_SIZE]; cur_size = INITIAL_SIZE; } TileList::~TileList() { delete[] tiles; } void TileList::addTile(const Tile &tile) { // O(1) (amortized) if (amount_tiles == cur_size) { // reached size limit, so allocate new array and move the old tiles cur_size *= 2; Tile *expanded_tiles = new Tile[cur_size]; for (int i = 0; i < amount_tiles; i++) { expanded_tiles[i] = tiles[i]; } delete[] tiles; tiles = expanded_tiles; } tiles[amount_tiles++] = tile; } void TileList::drawAll(QGraphicsScene *scene) const { // O(n) for (int i = 0; i < amount_tiles; i++) { (tiles + i)->draw(scene); } } int TileList::indexOfTopTile(int x, int y) const { // O(n) for (int i = amount_tiles - 1; i >= 0; --i) { if ((tiles + i)->contains(x, y)) { return i; } } return -1; } void TileList::shiftRight(int start, int end) { // e.g. amount_tiles=6, start=1, end=4: // 0 1 2 3 4 5 // 0 1 1 2 3 5 // O(n) for (int i = end; i > start; i--) { tiles[i] = tiles[i - 1]; } } void TileList::shiftLeft(int start, int end) { // e.g. amount_tiles=6, start=4, end=1: // 0 1 2 3 4 5 // 0 2 3 4 4 5 // O(n) for (int i = end; i < start; i++) { tiles[i] = tiles[i + 1]; } } void TileList::raise(int x, int y) { // 0 1 2 3 4 5 - // 0 1 2 3 4 5 3 // 0 1 2 4 5 5 3 // 0 1 2 4 5 3 - // O(n) int index = indexOfTopTile(x, y); if (index == -1 || index == amount_tiles - 1) { // no tile found, or tile is already at top return; } Tile tmpTile = tiles[index]; shiftLeft(amount_tiles - 1, index); tiles[amount_tiles - 1] = tmpTile; } void TileList::lower(int x, int y) { // 0 1 2 3 4 5 - // 0 1 2 3 4 5 3 // 0 0 1 2 4 5 3 // 3 0 1 2 4 5 - // O(n) int index = indexOfTopTile(x, y); if (index == -1 || index == 0) { // no tile found, or tile is already at bottom return; } Tile tmpTile = tiles[index]; shiftRight(0, index); tiles[0] = tmpTile; } void TileList::remove(int x, int y) { // V // 0 1 2 3 4 5 // 0 1 3 4 5 5 // 0 1 3 4 5 x // O(n) int index; if ((index = indexOfTopTile(x, y)) != -1) { shiftLeft(amount_tiles - 1, index); amount_tiles--; } } void TileList::removeAll(int x, int y) { // O(n^2) int index; while ((index = indexOfTopTile(x, y)) != -1) { shiftLeft(amount_tiles - 1, index); amount_tiles--; } }