Skip to content

Instantly share code, notes, and snippets.

@smoge
Created March 6, 2024 12:15
Show Gist options
  • Save smoge/411bd0aef037c64edf03b8f3c03a9734 to your computer and use it in GitHub Desktop.
Save smoge/411bd0aef037c64edf03b8f3c03a9734 to your computer and use it in GitHub Desktop.
APL Array implementation
// style reminiscent of APL as pairs of one-=dimentional vectors representing values and shape
#include <cmath>
#include <iostream>
#include <thread>
#include <vector>
// Structure to represent an APL-style array
struct APLArray {
std::vector<int> values; // Flat storage of array elements
std::vector<int> shape; // Dimensions of the array
// Constructor
APLArray(const std::vector<int> &values, const std::vector<int> &shape)
: values(values), shape(shape) {}
// Function to print the array in 3D format
void print3D() const {
if (shape.size() != 3) {
std::cout << "Array is not 3D." << std::endl;
return;
}
for (int i = 0; i < shape[0]; ++i) {
std::cout << "Slice " << i + 1 << ":" << std::endl;
for (int j = 0; j < shape[1]; ++j) {
for (int k = 0; k < shape[2]; ++k) {
std::cout << values[i * shape[1] * shape[2] + j * shape[2] + k]
<< " ";
}
std::cout << std::endl;
}
std::cout << std::endl;
}
}
};
// Function to process a segment of the APLArray
void processSegment(APLArray &array, size_t start, size_t end) {
for (size_t i = start; i < end; ++i) {
array.values[i] = std::pow(array.values[i],
2); // Example operation: squaring each element
}
}
// Function to parallel process the APLArray
void parallelProcessAPLArray(APLArray &array) {
size_t numThreads = std::thread::hardware_concurrency();
std::vector<std::thread> threads;
size_t totalElements = array.values.size();
size_t elementsPerThread = totalElements / numThreads;
for (size_t i = 0; i < numThreads; ++i) {
size_t start = i * elementsPerThread;
size_t end = (i + 1) * elementsPerThread;
if (i == numThreads - 1) {
end = totalElements; // Make sure the last segment includes the end of the
// array
}
threads.emplace_back(processSegment, std::ref(array), start, end);
}
// Wait for all threads to complete
for (auto &t : threads) {
t.join();
}
}
int main() {
// Example: a 2x2x3 array
APLArray myAPLArray({1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}, {2, 2, 3});
std::cout << "Original array in 3D format:" << std::endl;
myAPLArray.print3D();
parallelProcessAPLArray(myAPLArray);
std::cout << "Processed array in 3D format:" << std::endl;
myAPLArray.print3D();
return 0;
}
// OUTPUT
//
// Original array in 3D format:
// Slice 1:
// 1 2 3
// 4 5 6
// Slice 2:
// 7 8 9
// 10 11 12
// Processed array in 3D format:
// Slice 1:
// 1 4 9
// 16 25 36
// Slice 2:
// 49 64 81
// 100 121 144
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment