Compare commits

...

8 Commits

6 changed files with 325 additions and 378 deletions

View File

@@ -1,4 +1,4 @@
FROM alpine:3.22.0 AS builder
FROM alpine:3.22.1 AS builder
RUN apk add --no-cache \
libstdc++=14.2.0-r6 \
@@ -16,7 +16,7 @@ COPY *.cpp *.hpp Makefile ./
RUN make -j "$(nproc)"
FROM alpine:3.22.0
FROM alpine:3.22.1
RUN apk add --no-cache \
libstdc++=14.2.0-r6 \

View File

@@ -1,9 +1,15 @@
CC := g++ -m64 -std=c++17
OBJ_DIR := bin
SRC_DIR := .
# Optimizer flags
#CFLAGS := -Og -g -rdynamic -pg -ggdb3 -D__DEBUG
CFLAGS := -O4
CFLAGS := $(CFLAGS) -Wall -Werror -Wextra -Wno-error=unused-function -Wpedantic
CFLAGS := -O3
# Warning flags
CFLAGS := $(CFLAGS) -Wall -Werror -Wextra -Wpedantic -Wshadow -Wnon-virtual-dtor -Wold-style-cast -Wcast-align -Wunused -Woverloaded-virtual -Wconversion
CFLAGS := $(CFLAGS) -Wsign-conversion -Wnull-dereference -Wdouble-promotion -Wformat=2 -Wimplicit-fallthrough -Wmisleading-indentation -Wduplicated-cond
CFLAGS := $(CFLAGS) -Wduplicated-branches -Wlogical-op -Wuseless-cast -Wsuggest-override
# Hardening flags
CFLAGS := $(CFLAGS) -fstack-protector-strong -fcf-protection -fstack-clash-protection -fsanitize=undefined -fno-sanitize-recover=undefined
EXEC := $(OBJ_DIR)/data
SRC := $(wildcard $(SRC_DIR)/*.cpp)
HEADER := $(wildcard $(SRC_DIR)/*.hpp)

View File

@@ -1,4 +1,3 @@
#include <cassert>
#include <random>
#include "toolbox.hpp"
#include "data.hpp"
@@ -20,40 +19,24 @@ static constexpr bool is_sorted(const asp::Array<T>& a) noexcept {
}
template<typename T, size_t N>
static constexpr void test_sort(const std::array<int32_t, N>& gaps, const asp::Array<T>& original, void (* const fnc)(const asp::Array<T>&), const char* const title) noexcept {
#ifdef __DEBUG
printf("xxxxxxxxxxxxxxx IGNORE COPY ");
#endif
const asp::Array<T> a(original);
static constexpr void test_sort(const std::array<int32_t, N>& gaps, const asp::Array<T>& original, void (* const fnc)(asp::Array<T>&), const char* const title) noexcept {
asp::Array<T> a(original);
asp::measure_time_void(gaps, title, fnc, a);
#ifdef __DEBUG
const bool result = asp::measure_time<bool>(gaps, "=> Unit test", is_sorted<T>, a);
// asp::print(original);
// asp::print(a);
asp::formatted_row(gaps, { result ? "Success" : "Failure", "-", "-" });
#else
assert(is_sorted(a));
#endif
const bool result = is_sorted<T>(a);
asp::formatted_row(gaps, { result ? "=> Unit test success" : "=> Unit test failure", "-", "-" });
}
template<typename T, size_t N>
static void test_argsort(const std::array<int32_t, N>& gaps, const asp::Array<T>& original, asp::Array<size_t>(* const fnc)(const asp::Array<T>&), const char* const title) noexcept {
#ifdef __DEBUG
printf("xxxxxxxxxxxxxxx IGNORE COPY ");
#endif
const asp::Array<T> a(original);
static inline void test_sort(const std::array<int32_t, N>& gaps, const asp::Array<T>& original, asp::Array<size_t>(* const fnc)(asp::Array<T>&), const char* const title) noexcept {
asp::Array<T> a(original);
const asp::Array<size_t> indices = asp::measure_time<asp::Array<size_t>>(gaps, title, fnc, a);
#ifdef __DEBUG
const bool result = asp::measure_time<bool>(gaps, "=> Unit test", is_arg_sorted<T>, original, indices);
asp::formatted_row(gaps, { result ? "Success" : "Failure", "-", "-" });
#else
assert(is_arg_sorted(original, indices));
#endif
const bool result = is_arg_sorted<T>(original, indices);
asp::formatted_row(gaps, { result ? "=> Unit test success" : "=> Unit test failure", "-", "-" });
}
template<typename T>
static asp::Array<T> create_random_array(const size_t& n) noexcept {
asp::Array<T> original(n);
static inline asp::Array<T> create_random_array(const int64_t n) noexcept {
asp::Array<T> original((size_t(n)));
std::random_device rd;
std::default_random_engine gen(rd());
std::uniform_int_distribution<T> distribution(std::numeric_limits<T>::min(), std::numeric_limits<T>::max());
@@ -64,39 +47,33 @@ int32_t main(int32_t argc, char** argv) {
asp::toolbox_unit_test();
using array_type = uint16_t;
size_t N = (static_cast<size_t>(1)<<15) - 1;
// size_t N = std::numeric_limits<array_type>::max();
int64_t N = (static_cast<int64_t>(1)<<16) - 1;
// int64_t N = std::numeric_limits<array_type>::max();
if (argc > 2) {
fprintf(stderr, "Too many arguments\nUsage: ./data <ARRAY_SIZE>\n");
return EXIT_FAILURE;
} else if (argc == 2)
N = std::strtoul(argv[1], argv + strlen(argv[1]) + 1, 10);
N = std::strtol(argv[1], argv + strlen(argv[1]) + 1, 10);
char title[64];
sprintf(title, "Sorting %s elements of %s", asp::thousand_sep(N).c_str(), asp::format_byte_size(2 * N * sizeof(array_type)).c_str());
const std::array<int32_t, 3> gaps = { 48, -17, 25 };
sprintf(title, "Sorting %s elements of %s", asp::thousand_sep(N).c_str(), asp::format_byte_size(2 * uint64_t(N) * sizeof(array_type)).c_str());
constexpr std::array<int32_t, 3> gaps = { 48, -17, 25 };
asp::header(gaps, { title, "Time spent (ns)", "Formatted time spent" });
const asp::Array<array_type> original = asp::measure_time<asp::Array<array_type>>(gaps, "Creating random array", create_random_array<array_type>, N);
// const asp::Array<array_type> original = { 2, 5, 3, 0, 2, 3, 0, 3 };
// asp::print(original);
test_sort(gaps, original, asp::bubble_sort<array_type>, "Bubble sort");
test_argsort(gaps, original, asp::bubble_sort_arg<array_type>, "Bubble sort (arg)");
test_sort(gaps, original, asp::bubble_sort_arg<array_type>, "Bubble sort (arg)");
test_sort(gaps, original, asp::quicksort<array_type>, "Quicksort");
test_argsort(gaps, original, asp::quicksort_arg<array_type>, "Quicksort (arg)");
test_sort(gaps, original, asp::quicksort_arg<array_type>, "Quicksort (arg)");
test_sort(gaps, original, asp::quicksort_iter<array_type>, "Quicksort (iterative)");
test_argsort(gaps, original, asp::quicksort_arg_iter<array_type>, "Quicksort (iterative) (arg)");
test_sort(gaps, original, asp::quicksort_arg_iter<array_type>, "Quicksort (iterative) (arg)");
test_sort(gaps, original, asp::mergesort<array_type>, "Mergesort");
test_argsort(gaps, original, asp::mergesort_arg<array_type>, "Mergesort (arg)");
test_sort(gaps, original, asp::mergesort_arg<array_type>, "Mergesort (arg)");
test_sort(gaps, original, asp::insertion_sort<array_type>, "Insertion sort");
// test_argsort(gaps, original, asp::insertion_argsort<array_type>, "Insertion argsort");
// W.I.P
// test_sort(gaps, original, asp::counting_sort<array_type>, "Counting sort");
// test_argsort(gaps, original, asp::counting_sort_arg<array_type>, "Counting sort (arg)");
// test_sort(gaps, original, asp::radix_sort<array_type>, "Radix sort");
// test_argsort(gaps, original, asp::radix_sort_arg<array_type>, "Radix sort (arg)");
test_sort(gaps, original, asp::insertion_argsort<array_type>, "Insertion (arg)");
test_sort(gaps, original, asp::counting_sort<array_type>, "Counting sort");
test_sort(gaps, original, asp::radix_sort<array_type>, "Radix sort");
asp::footer(gaps);

367
data.hpp
View File

@@ -1,5 +1,4 @@
#pragma once
#include <memory>
#include <string_view>
#include <cstring>
#include <cstdio>
@@ -11,96 +10,104 @@
namespace asp {
template<typename T>
struct Array {
std::shared_ptr<T[]> data;
T* data = nullptr;
size_t length = 0;
size_t* refcount = nullptr;
constexpr Array(void) noexcept = delete;
constexpr Array(const size_t& size) noexcept : data(std::shared_ptr<T[]>(new T[size])), length(size) {
constexpr Array(const size_t& size) noexcept : data(new T[size]), length(size), refcount(new size_t(1)) {
#ifdef __DEBUG
printf("Creating array of size %lu\n", size);
#endif
}
constexpr Array(const std::initializer_list<size_t>& other) noexcept : data(std::shared_ptr<T[]>(new T[other.size()])), length(other.size()) {
constexpr Array(const std::initializer_list<size_t>& init_list) noexcept : data(new T[init_list.size()]), length(init_list.size()), refcount(new size_t(1)) {
#ifdef __DEBUG
printf("Copying array of size %lu\n", other.size());
printf("Copying initializer_list of size %lu\n", init_list.size());
#endif
memcpy(data.get(), other.begin(), length * sizeof(T));
memcpy(data, init_list.begin(), length * sizeof(T));
}
constexpr Array(const Array<T>& other) noexcept : data(std::shared_ptr<T[]>(new T[other.length])), length(other.length) {
constexpr Array(const Array<T>& other) noexcept : Array<T>(other.length) {
#ifdef __DEBUG
printf("Copying array of size %lu\n", other.length);
#endif
memcpy(data.get(), other.data.get(), length * sizeof(T));
memcpy(data, other.data, length * sizeof(T));
}
constexpr Array(Array&& other) noexcept {
#ifdef __DEBUG
printf("Moving array of size %lu\n", other.length);
#endif
if (refcount != nullptr){
delete[] data;
delete refcount;
}
data = other.data;
length = other.length;
refcount = other.refcount;
other.data = nullptr;
other.length = 0;
other.refcount = nullptr;
}
constexpr T& operator[](const size_t& index) const {
inline ~Array() noexcept {
if (refcount == nullptr)
return;
#ifdef __DEBUG
printf("Destructing array of size %lu and refcount %lu\n", length, *refcount);
#endif
if (--(*refcount) == 0){
#ifdef __DEBUG
printf("Freeing array of size %lu\n", length);
#endif
delete[] data;
data = nullptr;
delete refcount;
refcount = nullptr;
}
}
constexpr Array& operator=(const Array& other) noexcept {
if (this != &other) {
if (--(*refcount) == 0) {
delete[] data;
delete refcount;
}
data = other.data;
length = other.length;
refcount = other.refcount;
++(*refcount);
}
return *this;
}
constexpr T& operator[](const size_t& index) {
#ifdef __DEBUG
if (index > length) {
fprintf(stderr, "Index %ld out of range in Array of length %ld !\n", index, length);
throw std::out_of_range("Index out of range !");
}
#endif
return data.get()[index];
return data[index];
}
constexpr const T& operator[](const size_t& index) const {
#ifdef __DEBUG
if (index > length) {
fprintf(stderr, "Index %ld out of range in Array of length %ld !\n", index, length);
throw std::out_of_range("Index out of range !");
}
#endif
return data[index];
}
};
template<typename T>
constexpr int32_t print(const Array<T>& a, const char* const format) noexcept {
int32_t num_written = 0;
num_written += printf("[");
char formatter[256] = { 0 };
sprintf(formatter, "%s,", format);
for (size_t i = 0; i < a.length; ++i)
num_written += printf(formatter, a[i]);
sprintf(formatter, "%s]\n", format);
num_written += printf(formatter, a[a.length - 1]);
return num_written;
}
constexpr int32_t print(const Array<uint16_t>& a) noexcept {
return print(a, "%b");
}
constexpr int32_t print(const Array<int32_t>& a) noexcept {
return print(a, "%i");
}
constexpr int32_t print(const Array<uint32_t>& a) noexcept {
return print(a, "%u");
}
constexpr int32_t print(const Array<uint64_t>& a) noexcept {
return print(a, "%lu");
}
constexpr int32_t print(const Array<int16_t>& a) noexcept {
return print(a, "%i");
}
constexpr int32_t print(const std::string_view& s) noexcept {
return printf("%s\n", s.data());
}
constexpr int32_t print(const char* const s) noexcept {
return printf("%s\n", s);
}
template<typename T>
constexpr T& max(const Array<T>& a) noexcept {
T& max_el = a[0];
constexpr T max(const Array<T>& a) noexcept {
T max_el = a[0];
for (size_t i = 1; i < a.length; ++i)
if (a[i] > max_el)
max_el = a[i];
@@ -131,26 +138,19 @@ namespace asp {
inline Array<size_t> range(const size_t& n) noexcept {
Array<size_t> a(n);
return map(a, [](const size_t& i, const size_t&) -> const size_t& {
return map(a, [](const size_t i, const size_t) -> size_t {
return i;
});
}
template<typename T>
constexpr void swap(T* const a, T* const b) noexcept {
const T temp = *a;
*a = *b;
*b = temp;
}
template<typename T>
constexpr void bubble_sort(const Array<T>& a) noexcept {
constexpr void bubble_sort(Array<T>& a) noexcept {
size_t j = 0;
for (size_t i = 0; i < a.length; ++i) {
bool swapped = false;
for (j = i + 1; j < a.length; ++j)
if (a[i] > a[j]) {
swap(&a[i], &a[j]);
std::swap(a[i], a[j]);
swapped = true;
}
if (!swapped)
@@ -159,15 +159,15 @@ namespace asp {
}
template<typename T>
Array<size_t> bubble_sort_arg(const Array<T>& a) noexcept {
inline Array<size_t> bubble_sort_arg(Array<T>& a) noexcept {
Array<size_t> indices = range(a.length);
size_t j;
for (size_t i = 0; i < a.length; ++i) {
bool swapped = false;
for (j = i + 1; j < a.length; ++j)
if (a[i] > a[j]) {
swap(&indices[i], &indices[j]);
swap(&a[i], &a[j]);
std::swap(indices[i], indices[j]);
std::swap(a[i], a[j]);
swapped = true;
}
if (!swapped)
@@ -177,17 +177,17 @@ namespace asp {
}
template<typename T>
constexpr size_t qs_partition(const Array<T>& a, const size_t& l, const size_t& h) noexcept {
constexpr size_t qs_partition(Array<T>& a, const size_t& l, const size_t& h) noexcept {
size_t i = l - 1;
for (size_t j = l; j <= h; ++j)
if (a[j] < a[h])
swap(&a[++i], &a[j]);
swap(&a[++i], &a[h]);
std::swap(a[++i], a[j]);
std::swap(a[++i], a[h]);
return i;
}
template<typename T>
constexpr void quicksort(const Array<T>& a, const size_t& l, const size_t& h) noexcept {
constexpr void quicksort(Array<T>& a, const size_t& l, const size_t& h) noexcept {
if (l >= h)
return;
@@ -198,12 +198,12 @@ namespace asp {
}
template<typename T>
constexpr void quicksort(const Array<T>& a) noexcept {
constexpr void quicksort(Array<T>& a) noexcept {
quicksort(a, 0, a.length - 1);
}
template<typename T>
constexpr void quicksort_iter(const Array<T>& a, const size_t& l, const size_t& h) noexcept {
constexpr void quicksort_iter(Array<T>& a, const size_t& l, const size_t& h) noexcept {
// Create an auxiliary stack
const size_t total = h - l + 1;
@@ -246,25 +246,25 @@ namespace asp {
}
template<typename T>
constexpr void quicksort_iter(const Array<T>& a) noexcept {
constexpr void quicksort_iter(Array<T>& a) noexcept {
quicksort_iter(a, 0, a.length - 1);
}
template<typename T>
constexpr size_t qs_arg_partition(const Array<T>& a, const Array<size_t>& indices, const size_t& l, const size_t& h) noexcept {
constexpr size_t qs_arg_partition(Array<T>& a, Array<size_t>& indices, const size_t& l, const size_t& h) noexcept {
size_t i = l - 1;
for (size_t j = l; j <= h; ++j)
if (a[j] < a[h]){
swap(&a[++i], &a[j]);
swap(&indices[i], &indices[j]);
std::swap(a[++i], a[j]);
std::swap(indices[i], indices[j]);
}
swap(&indices[++i], &indices[h]);
swap(&a[i], &a[h]);
std::swap(indices[++i], indices[h]);
std::swap(a[i], a[h]);
return i;
}
template<typename T>
constexpr void quicksort_arg(const Array<T>& a, const Array<size_t>& indices, const size_t& l, const size_t& h) noexcept {
constexpr void quicksort_arg(Array<T>& a, Array<size_t>& indices, const size_t& l, const size_t& h) noexcept {
if (l >= h)
return;
@@ -275,19 +275,19 @@ namespace asp {
}
template<typename T>
Array<size_t> quicksort_arg(const Array<T>& other, const size_t& l, const size_t& h) noexcept {
inline Array<size_t> quicksort_arg(Array<T>& other, const size_t& l, const size_t& h) noexcept {
Array<size_t> indices = range(other.length);
quicksort_arg(other, indices, l, h);
return indices;
}
template<typename T>
Array<size_t> quicksort_arg(const Array<T>& a) noexcept {
inline Array<size_t> quicksort_arg(Array<T>& a) noexcept {
return quicksort_arg(a, 0, a.length - 1);
}
template<typename T>
constexpr void quicksort_arg_iter(const Array<T>& a, const Array<size_t>& indices, const size_t& l, const size_t& h) noexcept {
inline void quicksort_arg_iter(Array<T>& a, Array<size_t>& indices, const size_t& l, const size_t& h) noexcept {
// Create an auxiliary stack
const size_t total = h - l + 1;
// push initial values of l and h to stack
@@ -327,7 +327,7 @@ namespace asp {
}
template<typename T>
Array<size_t> quicksort_arg_iter(const Array<T>& a) noexcept {
inline Array<size_t> quicksort_arg_iter(Array<T>& a) noexcept {
Array<size_t> indices = range(a.length);
quicksort_arg_iter(a, indices, 0, a.length - 1);
return indices;
@@ -342,21 +342,21 @@ namespace asp {
constexpr ArgVal(const size_t& _i, const T& _v) noexcept : indice(_i), val(_v) {}
constexpr bool operator>(const ArgVal<T>& other) const noexcept {
return std::move(val > other.val);
return val > other.val;
}
constexpr bool operator<(const ArgVal<T>& other) const noexcept {
return std::move(val < other.val);
return val < other.val;
}
constexpr bool operator>=(const ArgVal<T>& other) const noexcept {
return std::move(val >= other.val);
return val >= other.val;
}
constexpr bool operator<=(const ArgVal<T>& other) const noexcept {
return std::move(val <= other.val);
return val <= other.val;
}
};
template<typename T>
constexpr void merge(const Array<T>& a, const size_t& l, const size_t& m, const size_t& r) noexcept {
constexpr void merge(Array<T>& a, const size_t& l, const size_t& m, const size_t& r) noexcept {
Array<T> left_arr(m - l + 1);
memcpy(&left_arr.data[0], &a[l], left_arr.length * sizeof(T));
@@ -377,7 +377,7 @@ namespace asp {
}
template<typename T>
constexpr void mergesort(const Array<T>& a, const size_t& l, const size_t& r) noexcept {
constexpr void mergesort(Array<T>& a, const size_t& l, const size_t& r) noexcept {
if (l >= r)
return;
@@ -388,33 +388,28 @@ namespace asp {
}
template<typename T>
constexpr void mergesort(const Array<T>& a) noexcept {
constexpr void mergesort(Array<T>& a) noexcept {
mergesort(a, 0, a.length - 1);
}
template<typename T>
Array<size_t> mergesort_arg(const Array<T>& a, const size_t& l, const size_t& r) noexcept {
inline Array<size_t> mergesort_arg(Array<T>& a) noexcept {
Array<ArgVal<T>> temp_vals(a.length);
map(temp_vals, [&a](const size_t& i, const ArgVal<T>&) -> const ArgVal<T> {
map(temp_vals, [&a](const size_t& i, const ArgVal<T>&) -> ArgVal<T> {
return ArgVal<T>(i, a[i]);
});
mergesort(temp_vals, l, r);
mergesort(temp_vals, 0, a.length - 1);
Array<size_t> indices(a.length);
return std::move(map(indices, [&temp_vals](const size_t& i, const size_t&) -> size_t {
return map(indices, [&temp_vals](const size_t& i, const size_t&) -> size_t {
return temp_vals[i].indice;
}));
});
}
template<typename T>
Array<size_t> mergesort_arg(const Array<T>& a) noexcept {
return mergesort_arg(a, 0, a.length - 1);
}
template<typename T>
constexpr void insertion_sort(const Array<T>& a) noexcept {
constexpr void insertion_sort(Array<T>& a) noexcept {
size_t j = 0;
for(size_t i = 1; i < a.length; ++i) {
T key = a[i];
@@ -425,146 +420,64 @@ namespace asp {
}
template<typename T>
Array<size_t> insertion_argsort(const Array<T>& a) noexcept {
Array<size_t> indices = range(a.length);
size_t j = 0;
for(size_t i = 1; i < a.length; ++i){
for(j = i; j > 0 && a[indices[j - 1]] > a[indices[i]]; --j)
indices[j] = indices[j - 1];
indices[j] = i;
}
return indices;
}
template<typename T>
constexpr void counting_sort(const Array<T>& a) noexcept {
const size_t N = a.length;
const T M = max(a);
const T exp = 10;
const T d = 128;
Array<T> countArray(M);
memset(&countArray[0], 0, M * sizeof(T));
foreach(a, [&countArray](const size_t, const T val) -> void {
++countArray[val];
inline Array<size_t> insertion_argsort(Array<T>& a) noexcept {
Array<ArgVal<T>> temp_vals(a.length);
map(temp_vals, [&a](const size_t& i, const ArgVal<T>&) -> ArgVal<T> {
return ArgVal<T>(i, a[i]);
});
for (T i = 1; i <= M; ++i)
countArray[i] += countArray[i - 1];
insertion_sort(temp_vals);
Array<T> output(N);
for (size_t i = N - 1; i > 0; --i){
output[countArray[a[i]] - 1] = a[i];
--countArray[a[i]];
}
memmove(&a[0], &output[0], a.length * sizeof(T));
Array<size_t> indices(a.length);
return map(indices, [&temp_vals](const size_t& i, const size_t&) -> size_t {
return temp_vals[i].indice;
});
}
template<typename T>
Array<size_t> counting_sort_arg(const Array<T>& a) noexcept {
Array<size_t> indices = range(a.length);
return indices;
inline void countsort(Array<T>& a, int64_t k, int64_t pos) noexcept {
Array<T> output(a.length + 1);
T max = T((a[0] / pos) % k);
for (size_t i = 1; i < a.length; ++i) {
const T val = a[i];
if (((val / pos) % k) > max)
max = val;
}
inline void countsort(int a[], int n, int pos){
int* output = new int[n + 1];
int max = (a[0] / pos) % 10;
for (int i = 1; i < n; i++) {
if (((a[i] / pos) % 10) > max)
max = a[i];
}
int* count = new int[max + 1];
for (int i = 0; i < max; ++i)
count[i] = 0;
for (int i = 0; i < n; i++)
count[(a[i] / pos) % 10]++;
for (int i = 1; i < 10; i++)
Array<T> count(max + 1);
memset(count.data, 0, count.length * sizeof(T));
for (size_t i = 0; i < a.length; ++i)
++count[size_t((a[i] / pos) % k)];
// Prefix sum
for (size_t i = 1; i < count.length; i++)
count[i] += count[i - 1];
for (int i = n - 1; i >= 0; i--) {
output[count[(a[i] / pos) % 10] - 1] = a[i];
count[(a[i] / pos) % 10]--;
}
for (int i = 0; i < n; i++)
a[i] = output[i];
delete[] output;
delete[] count;
for (size_t i = a.length - 1; i > 0; --i) {
const T val = a[i];
output[count[size_t((val / pos) % k)] - 1] = val;
--count[size_t((val / pos) % k)];
}
const T val = a[0];
output[count[size_t((val / pos) % k)] - 1] = val;
--count[size_t((val / pos) % k)];
memmove(a.data, output.data, a.length * sizeof(T));
}
// template<typename T>
// constexpr void radix_sort_256(T* a, const size_t& n) noexcept {
// //template<typename T>
// //void radix_sort(const Array<int32_t>& a) noexcept {
// if (n <= 1)
// //if (a.length <= 1)
// return;
//
// T* output = new T[n]; // output array
// size_t* const count = new size_t[256];
// T* originalArr = a; // So we know which was input
//
// for (size_t shift = 0, s = 0; shift < 4; shift++, s += 8) {
// // Zero the counts
// for (size_t i = 0; i < 256; i++)
// count[i] = 0;
//
// // Store count of occurrences in count[]
// for (size_t i = 0; i < n; i++)
// count[(a[i] >> s) & 0xff]++;
//
// // Change count[i] so that count[i] now contains
// // actual position of this digit in output[]
// for (size_t i = 1; i < 256; i++)
// count[i] += count[i - 1];
//
// // Build the output array
// for (int32_t i = n - 1; i >= 0; i--) {
// // precalculate the offset as it's a few instructions
// const size_t idx = (a[i] >> s) & 0xff;
//
// // Subtract from the count and store the value
// output[--count[idx]] = a[i];
// }
//
// // Copy the output array to input[], so that input[]
// // is sorted according to current digit
//
// // We can just swap the pointers
// swap(a, output);
// }
//
// // If we switched posize_ters an odd number of times,
// // make sure we copy before returning
// if (originalArr == output) {
// swap(a, output);
// for (size_t i = 0; i < n; i++)
// a[i] = output[i];
// }
//
// delete[] output, delete[] count;
// }
template<typename T>
inline void counting_sort(Array<T>& a) noexcept {
countsort<T>(a, max(a) + 1, 1);
}
constexpr void radix_sort_256(int32_t a[], int n){
int max = a[0];
for (int i = 1; i < n; i++)
template<typename T>
constexpr void radix_sort(Array<T>& a) noexcept {
constexpr int64_t k = 10;
T max = a[0];
for (size_t i = 1; i < a.length; i++)
if (a[i] > max)
max = a[i];
for (int pos = 1; max / pos > 0; pos *= 10)
countsort(a, n, pos);
for (int64_t pos = 1; max / pos > 0; pos *= k)
countsort(a, k, pos);
}
template<typename T>
constexpr void radix_sort(const Array<T>& a) noexcept {
radix_sort_256(a.data.get(), a.length);
}
// template<typename T>
// constexpr Array<size_t> radix_sort_arg(const Array<T>& a) noexcept {
// Array<T> indices = range(a.length);
//
// return indices;
// }
};

View File

@@ -1,24 +1,11 @@
#include <cassert>
#include <algorithm>
#include <array>
#include <limits>
#include <sstream>
#include "toolbox.hpp"
namespace asp {
/**
* @brief Swap two given memory values
*
* @tparam T Type of memory placeholder
* @param a Firat memory pointer
* @param b Second memory pointer
*/
template<typename T>
constexpr void swap(T* const a, T* const b) noexcept {
const T temp = *a;
*a = *b;
*b = temp;
}
/**
* @brief Convert a given number to string
*
@@ -31,12 +18,12 @@ namespace asp {
size_t i = 0;
for (; num > 0; num /= 10)
str[offset + i++] = num % 10 + '0';
str[offset + i++] = char(num % 10) + '0';
str[offset + i] = '\0';
for (size_t j = 0; j < i / 2; ++j)
swap(str + offset + j, str + offset + i - j - 1);
std::swap(str[offset + j], str[offset + i - j - 1]);
return i;
}
@@ -49,7 +36,7 @@ namespace asp {
*/
template<typename T>
static constexpr uint64_t u64(const T var) noexcept {
return static_cast<uint64_t>(var);
return uint64_t(var);
}
static constexpr const size_t STR_BUFFER_SIZE = 64;
@@ -77,10 +64,10 @@ namespace asp {
}
size_t j = 0;
for(int8_t i = static_cast<int8_t>(format_prefix.size() - 1) * 10; i >= 0; i -= 10){
for(uint8_t i = uint8_t(format_prefix.size() - 1) * 10; i > 0; i -= 10){
const uint64_t nsi = n >> i;
if(nsi > 0){
const int8_t idx = i / 10;
const uint8_t idx = i / 10;
j += ullstr(nsi, j, s);
for(int k = 0; format_prefix[idx][k] > 0; ++k)
s[j++] = format_prefix[idx][k];
@@ -88,6 +75,12 @@ namespace asp {
n &= u64(-1) >> (64 - i);
}
}
if(n > 0){
j += ullstr(n, j, s);
for(int k = 0; format_prefix[0][k] > 0; ++k)
s[j++] = format_prefix[0][k];
s[j++] = ' ';
}
/* Remove trailing character */
s[j - 1] = '\0';
@@ -111,7 +104,7 @@ namespace asp {
}
uint64_t res;
for (int8_t i = time_numbers.size() - 1; i >= 0; --i) {
for (uint8_t i = time_numbers.size() - 1; i > 0; --i) {
if (time >= time_numbers[i]) {
res = time / time_numbers[i];
time %= time_numbers[i];
@@ -121,6 +114,14 @@ namespace asp {
s[j++] = ' ';
}
}
if (time >= time_numbers[0]) {
res = time / time_numbers[0];
time %= time_numbers[0];
j += ullstr(res, j, s);
for(int k = 0; time_formats[0][k] > 0; ++k)
s[j++] = time_formats[0][k];
s[j++] = ' ';
}
/* Remove trailing character */
s[j - 1] = '\0';
@@ -130,94 +131,144 @@ namespace asp {
return ss;
}
struct separate_thousands : std::numpunct<char> {
char sep_;
separate_thousands(const char sep) noexcept : sep_(sep) {}
char_type do_thousands_sep() const override { return sep_; } // separate with commas
string_type do_grouping() const override { return "\3"; } // groups of 3 digit
};
/**
* @brief Format a given integer with a given seperator for each thousands.
*
* @param k Integer
* @param sep Thousand seperator
* @return Formatted integer
*/
std::string thousand_sep(const int64_t k, const char sep) noexcept {
std::ostringstream out;
out.imbue(std::locale(out.getloc(), new separate_thousands(sep)));
out << k;
return out.str();
}
/**
* @brief Format a given integer with ',' for each thousands.
*
* @param k Integer
* @return Formatted integer
*/
std::string thousand_sep(const int64_t k) noexcept {
return thousand_sep(k, ',');
}
/**
* @brief Run some unitary tests on format functions
*
*/
void toolbox_unit_test(void) noexcept {
assert(std::string("0B") == format_byte_size(u64(0)));
assert(std::string("1B") == format_byte_size(u64(1)));
assert(std::string("1KB") == format_byte_size(u64(1) << 10));
assert(std::string("1MB") == format_byte_size(u64(1) << 20));
assert(std::string("1GB") == format_byte_size(u64(1) << 30));
assert(std::string("0B") == format_byte_size(0));
assert(std::string("1B") == format_byte_size(1));
assert(std::string("1KB") == format_byte_size(1 << 10));
assert(std::string("1MB") == format_byte_size(1 << 20));
assert(std::string("1GB") == format_byte_size(1 << 30));
assert(std::string("1TB") == format_byte_size(u64(1) << 40));
assert(std::string("1PB") == format_byte_size(u64(1) << 50));
assert(std::string("1EB") == format_byte_size(u64(1) << 60));
// uint64_t_MAX == 2**64 == 18446744073709551615 == -1
assert(std::string("15EB 1023PB 1023TB 1023GB 1023MB 1023KB 1023B") == format_byte_size(u64(-1)));
assert(std::string("15EB 1023PB 1023TB 1023GB 1023MB 1023KB 1023B") == format_byte_size(std::numeric_limits<uint64_t>::max()));
assert(std::string("15EB 1023PB 1023TB 1023GB 1023MB 1023KB 1023B") == format_byte_size(18446744073709551615ull));
assert(std::string("10EB 1000PB 1000TB 1000GB 1000MB 1000KB 1000B") == format_byte_size(12656215539330294760ull));
// https://en.wikipedia.org/wiki/Unit_of_time
assert(std::string("0ns") == format_time_ns(u64(0)));
assert(std::string("1ns") == format_time_ns(u64(1)));
assert(std::string("10ns") == format_time_ns(u64(10)));
assert(std::string("1us") == format_time_ns(u64(1e3)));
assert(std::string("1ms") == format_time_ns(u64(1e6)));
assert(std::string("10ms") == format_time_ns(u64(1e7)));
assert(std::string("100ms") == format_time_ns(u64(1e8)));
assert(std::string("1s") == format_time_ns(u64(1e9)));
assert(std::string("10s") == format_time_ns(u64(1e10)));
assert(std::string("1m") == format_time_ns(u64(6e10)));
assert(std::string("1m 26s 400ms") == format_time_ns(u64(864e8)));
assert(std::string("1m 40s") == format_time_ns(u64(1e11)));
assert(std::string("16m 40s") == format_time_ns(u64(1e12)));
assert(std::string("1h") == format_time_ns(u64(36e11)));
assert(std::string("1j") == format_time_ns(u64(864e11)));
assert(std::string("1w") == format_time_ns(u64(6048e11)));
assert(std::string("1w 4j 13h 46m 40s") == format_time_ns(u64(1e15)));
assert(std::string("2w") == format_time_ns(u64(12096e11)));
assert(std::string("3w 6j 5h 5m 35s 800ms") == format_time_ns(u64(23511358e8)));
assert(std::string("3w 6j 7h 43m 4s 700ms") == format_time_ns(u64(23605847e8)));
assert(std::string("3w 6j 7h 43m 11s 600ms") == format_time_ns(u64(23605916e8)));
assert(std::string("3w 6j 13h 18m 33s 200ms") == format_time_ns(u64(23807132e8)));
assert(std::string("4w 1j 12h 44m 2s 900ms") == format_time_ns(u64(25514429e8)));
assert(std::string("1M") == format_time_ns(u64(26298e11)));
assert(std::string("1M 1w 2j 13h 30m") == format_time_ns(u64(3456e12)));
assert(std::string("4M 4j 6h") == format_time_ns(u64(108864e11)));
assert(std::string("11M 2w 5j 13h 22m 48s") == format_time_ns(u64(30617568e9)));
assert(std::string("11M 4w 2j 4h 30m") == format_time_ns(u64(31536e12)));
assert(std::string("1y") == format_time_ns(u64(315576e11)));
assert(std::string("11M 4w 2j 10h 18m 45s") == format_time_ns(u64(31556925e9)));
assert(std::string("11M 4w 2j 10h 19m 12s") == format_time_ns(u64(31556952e9)));
assert(std::string("1y 9m 9s") == format_time_ns(u64(31558149e9)));
assert(std::string("1y 18h") == format_time_ns(u64(316224e11)));
assert(std::string("4y") == format_time_ns(u64(1262304e11)));
assert(std::string("5y") == format_time_ns(u64(157788e12)));
assert(std::string("10y") == format_time_ns(u64(315576e12)));
assert(std::string("15y") == format_time_ns(u64(473364e12)));
assert(std::string("20y") == format_time_ns(u64(631152e12)));
assert(std::string("31y 8M 1w 19h 46m 40s") == format_time_ns(u64(1e18)));
assert(std::string("50y") == format_time_ns(u64(157788e13)));
assert(std::string("1c") == format_time_ns(u64(315576e13)));
// uint64_t_MAX == 2**64 == 18446744073709551615 == -1
assert(std::string("5c 84y 6M 2w 1j 8h 34m 33s 709ms 551us 615ns") == format_time_ns(u64(-1)));
assert(std::string("0ns") == format_time_ns(0));
assert(std::string("1ns") == format_time_ns(1));
assert(std::string("10ns") == format_time_ns(10));
assert(std::string("1us") == format_time_ns(1e3));
assert(std::string("1ms") == format_time_ns(1e6));
assert(std::string("10ms") == format_time_ns(1e7));
assert(std::string("100ms") == format_time_ns(1e8));
assert(std::string("1s") == format_time_ns(1e9));
assert(std::string("10s") == format_time_ns(1e10));
assert(std::string("1m") == format_time_ns(6e10));
assert(std::string("1m 26s 400ms") == format_time_ns(864e8));
assert(std::string("1m 40s") == format_time_ns(1e11));
assert(std::string("16m 40s") == format_time_ns(1e12));
assert(std::string("1h") == format_time_ns(36e11));
assert(std::string("1j") == format_time_ns(864e11));
assert(std::string("1w") == format_time_ns(6048e11));
assert(std::string("1w 4j 13h 46m 40s") == format_time_ns(1e15));
assert(std::string("2w") == format_time_ns(12096e11));
assert(std::string("3w 6j 5h 5m 35s 800ms") == format_time_ns(23511358e8));
assert(std::string("3w 6j 7h 43m 4s 700ms") == format_time_ns(23605847e8));
assert(std::string("3w 6j 7h 43m 11s 600ms") == format_time_ns(23605916e8));
assert(std::string("3w 6j 13h 18m 33s 200ms") == format_time_ns(23807132e8));
assert(std::string("4w 1j 12h 44m 2s 900ms") == format_time_ns(25514429e8));
assert(std::string("1M") == format_time_ns(26298e11));
assert(std::string("1M 1w 2j 13h 30m") == format_time_ns(3456e12));
assert(std::string("4M 4j 6h") == format_time_ns(108864e11));
assert(std::string("11M 2w 5j 13h 22m 48s") == format_time_ns(30617568e9));
assert(std::string("11M 4w 2j 4h 30m") == format_time_ns(31536e12));
assert(std::string("1y") == format_time_ns(315576e11));
assert(std::string("11M 4w 2j 10h 18m 45s") == format_time_ns(31556925e9));
assert(std::string("11M 4w 2j 10h 19m 12s") == format_time_ns(31556952e9));
assert(std::string("1y 9m 9s") == format_time_ns(31558149e9));
assert(std::string("1y 18h") == format_time_ns(316224e11));
assert(std::string("4y") == format_time_ns(1262304e11));
assert(std::string("5y") == format_time_ns(157788e12));
assert(std::string("10y") == format_time_ns(315576e12));
assert(std::string("15y") == format_time_ns(473364e12));
assert(std::string("20y") == format_time_ns(631152e12));
assert(std::string("31y 8M 1w 19h 46m 40s") == format_time_ns(1e18));
assert(std::string("50y") == format_time_ns(157788e13));
assert(std::string("1c") == format_time_ns(315576e13));
assert(std::string("5c 84y 6M 2w 1j 8h 34m 33s 709ms 551us 615ns") == format_time_ns(std::numeric_limits<uint64_t>::max()));
assert(std::string("5c 84y 6M 2w 1j 8h 34m 33s 709ms 551us 615ns") == format_time_ns(18446744073709551615ull));
assert(std::string("1c 10y 10M 3w 6j 10h 10m 10s 100ms 100us 100ns") == format_time_ns(3500003410100100100ull));
}
assert(std::string("1c 10y 10M 3w 6j 10h 10m 10s 100ms 100us 100ns") == format_time_ns(3500003410100100100));
std::string thousand_sep(const uint64_t& k, const char& sep) noexcept {
std::string s = "", n = std::to_string(k);
assert(std::string("0") == thousand_sep(0));
assert(std::string("1") == thousand_sep(1));
assert(std::string("10") == thousand_sep(10));
assert(std::string("100") == thousand_sep(100));
assert(std::string("1,000") == thousand_sep(1e3));
assert(std::string("10,000") == thousand_sep(1e4));
assert(std::string("100,000") == thousand_sep(1e5));
assert(std::string("1,000,000") == thousand_sep(1e6));
assert(std::string("10,000,000") == thousand_sep(1e7));
assert(std::string("100,000,000") == thousand_sep(1e8));
assert(std::string("1,000,000,000") == thousand_sep(1e9));
assert(std::string("10,000,000,000") == thousand_sep(1e10));
assert(std::string("100,000,000,000") == thousand_sep(1e11));
assert(std::string("1,000,000,000,000") == thousand_sep(1e12));
assert(std::string("10,000,000,000,000") == thousand_sep(1e13));
assert(std::string("100,000,000,000,000") == thousand_sep(1e14));
assert(std::string("1,000,000,000,000,000") == thousand_sep(1e15));
assert(std::string("10,000,000,000,000,000") == thousand_sep(1e16));
assert(std::string("100,000,000,000,000,000") == thousand_sep(1e17));
assert(std::string("1,000,000,000,000,000,000") == thousand_sep(1e18));
assert(std::string("1,234,567,890") == thousand_sep(1234567890));
assert(std::string("9,876,543,210") == thousand_sep(9876543210));
assert(std::string("9,223,372,036,854,775,807") == thousand_sep(std::numeric_limits<int64_t>::max()));
uint8_t c = 0;
for (int64_t i = int64_t(n.size()) - 1; i >= 0; --i) {
++c;
s.push_back(n[i]);
if (c == 3) {
s.push_back(sep);
c = 0;
}
}
std::reverse(s.begin(), s.end());
if (s.size() % 4 == 0)
s.erase(s.begin());
return s;
}
std::string thousand_sep(const uint64_t& k) noexcept {
return thousand_sep(k, ',');
assert(std::string("-1") == thousand_sep(-1));
assert(std::string("-10") == thousand_sep(-10));
assert(std::string("-100") == thousand_sep(-100));
assert(std::string("-1,000") == thousand_sep(-1e3));
assert(std::string("-10,000") == thousand_sep(-1e4));
assert(std::string("-100,000") == thousand_sep(-1e5));
assert(std::string("-1,000,000") == thousand_sep(-1e6));
assert(std::string("-10,000,000") == thousand_sep(-1e7));
assert(std::string("-100,000,000") == thousand_sep(-1e8));
assert(std::string("-1,000,000,000") == thousand_sep(-1e9));
assert(std::string("-10,000,000,000") == thousand_sep(-1e10));
assert(std::string("-100,000,000,000") == thousand_sep(-1e11));
assert(std::string("-1,000,000,000,000") == thousand_sep(-1e12));
assert(std::string("-10,000,000,000,000") == thousand_sep(-1e13));
assert(std::string("-100,000,000,000,000") == thousand_sep(-1e14));
assert(std::string("-1,000,000,000,000,000") == thousand_sep(-1e15));
assert(std::string("-10,000,000,000,000,000") == thousand_sep(-1e16));
assert(std::string("-100,000,000,000,000,000") == thousand_sep(-1e17));
assert(std::string("-1,000,000,000,000,000,000") == thousand_sep(-1e18));
assert(std::string("-1,234,567,890") == thousand_sep(-1234567890));
assert(std::string("-9,876,543,210") == thousand_sep(-9876543210));
assert(std::string("-9,223,372,036,854,775,808") == thousand_sep(std::numeric_limits<int64_t>::min()));
}
}

View File

@@ -18,8 +18,8 @@ namespace asp {
std::string format_time(const uint64_t) noexcept;
std::string format_time_ns(uint64_t) noexcept;
void toolbox_unit_test(void) noexcept;
std::string thousand_sep(const uint64_t&, const char&) noexcept;
std::string thousand_sep(const uint64_t&) noexcept;
std::string thousand_sep(const int64_t, const char) noexcept;
std::string thousand_sep(const int64_t) noexcept;
/**
* @brief Print a formatted row of titles with of gaps seperated by a separator.
@@ -90,7 +90,7 @@ namespace asp {
const auto start = time();
fnc(std::forward<Args>(args)...);
const long long timespent = duration_ns(time() - start);
formatted_row(gaps, { step_name, thousand_sep(timespent).c_str(), format_time_ns(timespent).c_str() });
formatted_row(gaps, { step_name, thousand_sep(timespent).c_str(), format_time_ns(uint64_t(timespent)).c_str() });
}
template <typename T, typename F, size_t N, typename... Args>
@@ -101,7 +101,7 @@ namespace asp {
const auto start = time();
const T res = fnc(std::forward<Args>(args)...);
const long long timespent = duration_ns(time() - start);
formatted_row(gaps, { step_name, thousand_sep(timespent).c_str(), format_time_ns(timespent).c_str() });
formatted_row(gaps, { step_name, thousand_sep(timespent).c_str(), format_time_ns(uint64_t(timespent)).c_str() });
return res;
}
};