Coding Exercise
Constructing a 3D Array
Implement a function GetSpace such that that it allocates a 3D array of ints of dimensions x, y, and z on the heap. You can find the original coding exercise here.
Requirements
Return an
int***.You cannot use any data structures (such as
vector).You must initialize all values to std::numeric_limits::min() during allocation without a for-loop. Cracked developers prefer STL algorithms to raw loops.
Consider edge-cases fully. Return
nullptrwhen encountering invalid inputs.
Test Cases
Test case inputs are formatted as x,y,z coordinates. For example, 4,5,6 is size_t x = 4, y = 5, z = 6;.
For more such puzzles, visit getcracked.io.
My Implementation
// Problem: https://getcracked.io/problem/8/3d-space?language=Cpp
// Date: 06-Jan-2025
// Compiler Explorer: https://compiler-explorer.com/z/d7PzdexEj
#include <cstdlib>
#include <limits>
#include <memory>
#include <print>
#include <iostream>
#include <algorithm>
int*** GetSpace(size_t x, size_t y, size_t z) {
if(x == 0 || y == 0 || z == 0)
return nullptr;
int*** A = static_cast<int***>(std::malloc(sizeof(int**) * z));
std::for_each(A, A + z, [=](int**& pp){
pp = static_cast<int**>(std::malloc(sizeof(int*) * y));
std::for_each(pp, pp + y, [=](int*& p){
p = static_cast<int*>(std::malloc(sizeof(int) * x));
std::uninitialized_fill(p, p + x, std::numeric_limits<int>::min());
});
});
return A;
}
int main(){
auto*** arr = GetSpace(2, 3, 4);
std::cout << arr[0][0][0] << "\n";
}References
- Coding exercises on getcracked.io