Skip to content

Instantly share code, notes, and snippets.

@gatchamix
Last active March 12, 2020 15:49
Show Gist options
  • Save gatchamix/469cef3686aedd801c2f960e83b64edc to your computer and use it in GitHub Desktop.
Save gatchamix/469cef3686aedd801c2f960e83b64edc to your computer and use it in GitHub Desktop.
scalable cache friendly spiral sequence generation (SNSystems)
#include <cstddef>
#include <algorithm>
#include <array>
#include <iostream>
using std::size_t;
auto constexpr calculate(size_t row, size_t column, size_t width, size_t height, size_t value = 0)
{
--width;
--height;
auto const ring = std::min({ row, column, width - column, height - row });
auto const doublering = 2 * ring;
value += doublering * (width + height + 2 - doublering);
row -= ring;
column -= ring;
width -= (2 * ring);
height -= (2 * ring);
if (row == 0 || column == width)
{
return value + row + column;
}
else
{
auto const max = value + (width + height) * 2;
return max - row - column;
}
}
template <size_t width, size_t height>
constexpr auto generate_spiral(size_t start = 0)
{
auto data = std::array<std::array<size_t, width>, height>{};
for (auto row = 0; row < height; ++row)
{
for (auto column = size_t{}; column < width; ++column)
{
data[row][column] = calculate(row, column, width, height, start);
}
}
return data;
}
int main()
{
constexpr auto spiral = generate_spiral<9, 12>(100);
for (auto&& rows : spiral)
{
for (auto&& val : rows)
{
std::cout << val << " ";
}
std::cout << '\n';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment