|
| 1 | + |
| 2 | +#ifndef LIB_INCLUDE_TICK_ARRAY_SPARSE2D_RANDOM2D_H_ |
| 3 | +#define LIB_INCLUDE_TICK_ARRAY_SPARSE2D_RANDOM2D_H_ |
| 4 | + |
| 5 | +#include <random> |
| 6 | + |
| 7 | +template <typename T, typename MAJ> |
| 8 | +std::shared_ptr<SparseArray2d<T, MAJ>> SparseArray2d<T, MAJ>::RANDOM(size_t rows, size_t cols, T density, T seed) { |
| 9 | + if (density < 0 || density > 1) |
| 10 | + throw std::runtime_error("Invalid sparse density, must be between 0 and 1"); |
| 11 | + |
| 12 | + size_t size = std::floor(rows * cols * density); |
| 13 | + auto arr = SSparseArray2d<T, MAJ>::new_ptr(rows, cols, size); |
| 14 | + |
| 15 | + std::mt19937_64 generator; |
| 16 | + if (seed > 0) { |
| 17 | + generator = std::mt19937_64(seed); |
| 18 | + } else { |
| 19 | + std::random_device r; |
| 20 | + std::seed_seq seed_seq{r(), r(), r(), r(), r(), r(), r(), r()}; |
| 21 | + generator = std::mt19937_64(seed_seq); |
| 22 | + } |
| 23 | + std::uniform_real_distribution<T> dist; |
| 24 | + auto data = arr->data(); |
| 25 | + for (size_t i = 0; i < size; i++) data[i] = dist(generator); |
| 26 | + |
| 27 | + size_t nnz = size; |
| 28 | + std::vector<size_t> nnz_row(rows, 0); |
| 29 | + |
| 30 | + size_t index = 0; |
| 31 | + while (nnz > 0) { |
| 32 | + std::uniform_int_distribution<size_t> dist_int(1, 100); // to do 50 50 |
| 33 | + if (dist_int(generator) > 50) { |
| 34 | + nnz_row[index]++; |
| 35 | + nnz--; |
| 36 | + } |
| 37 | + index++; |
| 38 | + if (index >= rows) index = 0; |
| 39 | + } |
| 40 | + |
| 41 | + index = 0; |
| 42 | + auto indices = arr->indices(); |
| 43 | + for (size_t i : nnz_row) { |
| 44 | + std::vector<size_t> indice_comb; |
| 45 | + for (size_t j = 0; j < cols; j++) indice_comb.emplace_back(j); |
| 46 | + std::shuffle(indice_comb.begin(), indice_comb.end(), generator); |
| 47 | + for (size_t j = 0; j < i; j++) { |
| 48 | + indices[index++] = indice_comb[j]; |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + // if (index != arr->indices().size() - 1) |
| 53 | + // std::runtime_error("Uh something is wrong"); |
| 54 | + |
| 55 | + auto row_indices = arr->row_indices(); |
| 56 | + row_indices[0] = 0; |
| 57 | + for (size_t i = 1; i < rows + 1; i++) row_indices[i] = row_indices[i - 1] + nnz_row[i - 1]; |
| 58 | + |
| 59 | + return arr; |
| 60 | + } |
| 61 | + |
| 62 | +#endif // LIB_INCLUDE_TICK_ARRAY_SPARSE2D_RANDOM2D_H_ |
0 commit comments