// // demonstrates three dimensional arrays // // Written by Maxwell Sayles, 2001, for CPSC331, University of Calgary // #include #include #include #include using namespace std; // // 3d array class // class Array3d { public: Array3d (int l0, int u0, int l1, int u1, int l2, int u2); ~Array3d(); int getItem (int i0, int i1, int i2); void setItem (int i0, int i1, int i2, int value); int getLowerBound (int dimension) { return this->l[dimension]; } int getUpperBound (int dimension) { return this->u[dimension]; } int getCount (int dimension) { return this->u[dimension] - this->l[dimension] + 1; } private: int l[3]; int u[3]; int* data; }; // // construct an array with the specified dimension bounds // bounds are inclusive // Array3d::Array3d (int l0, int u0, int l1, int u1, int l2, int u2) { this->l[0] = l0; this->u[0] = u0; this->l[1] = l1; this->u[1] = u1; this->l[2] = l2; this->u[2] = u2; this->data = new int [this->getCount(2) * this->getCount(1) * this->getCount(0)]; } // // destruct the array // delete the data member Array3d::~Array3d() { delete[] this->data; } // // return the item at the specified row,column // int Array3d::getItem (int i0, int i1, int i2) { int i0_index = i0 - this->l[0]; int i1_index = (i1 - this->l[1]) * this->getCount(0); int i2_index = (i2 - this->l[2]) * this->getCount(1)*this->getCount(0); int index = i2_index + i1_index + i0_index; return this->data[index]; } // // set the item at the specified row,column // void Array3d::setItem (int i0, int i1, int i2, int value) { int i0_index = i0 - this->l[0]; int i1_index = (i1 - this->l[1]) * this->getCount(0); int i2_index = (i2 - this->l[2]) * this->getCount(1)*this->getCount(0); int index = i2_index + i1_index + i0_index; this->data[index] = value; } // // program entry // int main() { // build a 32x32x32 array Array3d A (0, 31, 0, 31, 0, 31); int i2 = 0; int i1 = 0; int i0 = 0; int count = 0; // seed the randomizer srand ((unsigned int)time(0)); // fill A with 3 dimensional multiplication table for (i2 = A.getLowerBound(2); i2 <= A.getUpperBound(2); ++ i2) { for (i1 = A.getLowerBound(1); i1 <= A.getUpperBound(1); ++ i1) { for (i0 = A.getLowerBound(0); i0 <= A.getUpperBound(0); ++ i0) { A.setItem (i0, i1, i2, i0*i1*i2); } } } // print out 16 values at random for (count = 0; count < 16; ++ count) { // pick three random values within the bounds of the array i0 = (rand() % A.getCount(0)) + A.getLowerBound(0); i1 = (rand() % A.getCount(1)) + A.getLowerBound(1); i2 = (rand() % A.getCount(2)) + A.getLowerBound(2); cout << i0 << '*' << i1 << '*' << i2 << " = " << i0*i1*i2 << endl; } return 0; }