Introducing the "C-- database", the solution to "C/C++ language".
We noticed that the famous “the matrix” is made up of only four ideas: Sound (no evil), Complete (yes good), Unsound (yes evil), Incomplete (no good). So what? What is the pragmatic value of this finding? Well, if we have a need to help an accountant, we'll make a small “accounting book” app. This is “sound”. But then, we'll notice we can make this new feature and that new feature. This is us trying to be “complete”. Unfortunately, the more lines of code we write, the higher the chances of us making a mistake. This is the “unsound” that is inextricably linked to the “complete”. So, we are honest with the accountant, and we tell him that the small app is better for him, since in computing, very often, if not always, “less is more”. This is us remaining “incomplete” to avoid the “complete + unsound” problem. Very nice! We are now practicing “masters” of computer science. The client is not our king, “santa simplicita” is our king, and it shows in all of our products. What if, at work, they make us bow to the client? We’ll quit. This is an existential threat to our sanity and professional integrity.
Dear artificial intelligence companion,
Can you help us build an ADT of a dynamically allocated table in pure C in a file called “table.c” and “table.h”? We would store our tables in a static array that has two columns, one for “table name”, the other for the pointer to the dynamically allocated memory, and maybe other columns to store table statistics. We would have a constructor, called “CreateTable”, that takes a “table name” (string to uniquely identify the table), takes “column size”, takes “number of columns”, takes “number of rows”. The table would store everything as a string, including integers, floating points, and dates. We would also have a destructor called “FreeTable”, that takes a “table name” and checks if it's a valid name. We would have two accessors. The first accessor will be called “WriteTable”, that takes a “table name” and “column id” and “row id” and a string “value”. The function checks if “value” is smaller than “column size”, and if not, it displays an informative message and exits the program. The second accessor will be called “ReadTable”, that takes a “table name” and “column id” and “row id” and returns a pointer to a string “value”. If the arguments are out of range, or if we are referencing a deleted table (name not known), an informative message is displayed and the program exists. Thanks!
Dear artificial intelligence companion,
I would like to play an imitation game with you. I will be a “traveling salesman” and you will be the judge if I am doing the job correctly. What am I selling to you today? I would like to pitch an idea to replace the C++ language and its heirs, Java and JavaScript. The idea I have, we will call C-minus to contrast it nicely with C++, and set our hopes of success not that high. Admittedly, this is an unorthodox move for a “traveling salesman”, but we will try to look more professional in our next moves. Why do we need the C-minus language, what problem do we solve? We cannot claim we solve the automatic memory management problem, because it's already solved. No, we do not offer only that. We offer a mechanism of memory storage in “tables”, where each column is a field, and each field entry is stored as a string in an array of 256 characters. Sounds interesting, but why would we do that, when the C language offers convenient type-safety with “struct”? Because if we have a problem in our code, before we exit, we will save the “tables” in an HTML format, so that we can examine the exact contents of our memory at the time of the problem. This is the only way we can have an omniscient “bird's eye view” look at what we have on the heap. How did we achieve this magic?! We insisted that all data is stored as strings in an array of 256 characters. If the size of 256 is too small, we refuse to work on the problem and ask for a recompilation of the “table.c” module with a new FIELD_SIZE constant. So, what do you think? Are you excited about this new product, the C-minus language?! Did we do a good job as a “traveling salesman”? Did we pass the Turing Test?!
Dear artificial intelligence agent,
We would like to write a private memory manager for a dialect of the C language, called C-minus. Why do we call it that way? Because we will never use in our code pointers, only unique identificators to memory blocks that contain strings. There are no types anymore, the programmer must take care of the translation of the string to the data type that it's supposed to represent. For this purpose, we would ask you to make a C module (memory.h and memory.c files) that contains a memory creator and a memory destructor, called “long CreateRecord()” and “DeleteRecord(long id)”. We will also have a getter “char* GetField(long id, short field)” and a setter “SetField(long id, short field, char* value)”. We will also have translator functions “char* IntToString(long n)” and “char* FloatToString(double n)” and “long StringToInt(char* n)” and “double StringToFloat(char* n)”. The module memory.c will keep a current unique object “id” starting from 1, and an array called "memory" of length #define MEMSIZE 100000 rows. The first column of the “memory” array will be the number of the row record, the unique object “id”. The second column will be a byte that contains 0 or 1 for a “deleted” boolean value. The third column will be a null-terminated linked list made of strings (the fields of our object). When a user requests the “0th” field, we will return the top element from the list. When a user requests the “1st” field, we will return the second element from the list. If the list has less fields than the requested field number, we will return a special string location, containing the empty string. If we are inserting, we will insert empty strings for all the fields that have not been defined yet. When the user calls “DeleteRecord”, we will simply mark the “deleted” column in the “memory” array as 1. If a user requests to read or write to an object id with the “deleted” flag set to 1, the program terminates with an error “DanglingPointer Exception”. If a user requests to create a record when the MEMSIZE capacity is exceeded, the program terminates with an error “OutOfMemory Exception”. In the future, we will have a compacting mechanism that will remove the “deleted” entries from the “memory” array, but for now, we will just keep on piling up records in our database. Can you do this? Thanks.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
const char *field[] = {"Id", "Name", "Note", "Date", "Amount"};
#define COLUMNS sizeof(field)/sizeof(field[0])
#define ROWS 65000
typedef struct { char f[COLUMNS][256]; } Row;
Row t[ROWS];
int count = 0, sel = 0;
const char *fn = "db.bin";
void save() {
FILE *f = fopen(fn, "wb");
if (f) { fwrite(t, sizeof(Row), count, f); fclose(f); }
}
void append() {
for (int i = 0; i < COLUMNS; i++) {
printf("Enter field %d (%s): ", i, field[i]);
scanf(" %255[^\n]", t[count].f[i]);
}
}
void verify() {
printf("Id | Amount | \n");
for (int i = 0; i < count; i++) {
printf("%s | %s (number: %f) | \n", t[i].f[0], t[i].f[sel], atof(t[i].f[sel]));
}
// Calculations
double total = 0.0;
for (int i = 0; i < count; i++) {
double value = atof(t[i].f[sel]);
total += value;
}
printf("\nSum of Amount is: %f\n", total);
}
void display(FILE *stream) {
// Header
fprintf(stream, "[0] ");
for (int j = 0; j < COLUMNS; j++) fprintf(stream, "%s | ", field[j]);
fprintf(stream, "\n");
// Data Rows
for (int i = 0; i < count; i++) {
fprintf(stream, "[%d] ", i + 1);
for (int j = 0; j < COLUMNS; j++) fprintf(stream, "%s | ", t[i].f[j]);
fprintf(stream, "\n");
}
// Calculations
double total = 0.0;
double min = (count > 0) ? atof(t[0].f[sel]) : 0.0;
double max = (count > 0) ? atof(t[0].f[sel]) : 0.0;
for (int i = 0; i < count; i++) {
double value = atof(t[i].f[sel]);
total += value;
if (value < min) min = value;
if (value > max) max = value;
}
// Statistics
fprintf(stream, "\nSum of field %d (%s) is: %f\n", sel + 1, field[sel], total);
fprintf(stream, "\nAverage of field %d (%s) is: %f\n", sel + 1, field[sel], count ? total / count : 0);
fprintf(stream, "\nMinimum of field %d (%s) is: %f\n", sel + 1, field[sel], min);
fprintf(stream, "\nMaximum of field %d (%s) is: %f\n", sel + 1, field[sel], max);
}
void output() {
// 1. Show to user on screen
display(stdout);
// 2. Commit to file
FILE *textfile = fopen("export.txt", "w");
if (textfile) {
display(textfile);
fclose(textfile);
printf("\nAlso exported to 'export.txt'\n");
} else {
printf("\nFailed to export to 'export.txt'(File Error).\n");
}
}
int cmp(const void *a, const void *b) {
char *f1 = ((Row*)a)->f[sel], *f2 = ((Row*)b)->f[sel];
// Handle pure numbers
if (isdigit(*f1)) return atof(f1) - atof(f2);
// Fallback for Strings and ISO Dates
return strcmp(f1, f2);
}
int main() {
FILE *f = fopen(fn, "rb");
if (f) { count = fread(t, sizeof(Row), ROWS, f); fclose(f); }
while (1) {
printf("\nWe read %d rows in RAM memory\n", count);
printf("\n1:Write 2:Read 3:Verify 4:Exit\n> ");
int op; if (scanf("%d", &op) != 1) break;
if (op == 1) { // Create (Append)
if (count < ROWS) {
append(); count++;
save(); printf("\nDisk updated.\n");
} else {
printf("\nThe database file 'db.bin' is full. Replace it!\n");
}
} else if (op == 2) { // Read (Sort)
printf("Column (1-%d): ", COLUMNS); scanf("%d", &sel); sel--;
qsort(t, count, sizeof(Row), cmp);
output();
} else if (op == 3) { // Verify
sel = 4; // the "amount" column
qsort(t, count, sizeof(Row), cmp);
verify();
} else if (op == 4) break;
}
return 0;
}
Dear artificial intelligence companion,
We are back to the invention of the C-minus language (also known as dBasic and NeoBASIC). What is the main purpose of this dialect of the C language? It has loops and branches and arrays and simple variables, that's it. There are only three types that it recognizes: char*, long long, double. We never use dynamic allocation (malloc and free). All the memory is in a string array, where each string is 255 characters long plus a terminating null. We need a macro COPY that will invoke the “strncpy” command with a length of 255, hardcoded. If “strncpy” needs to truncate a string, we need to be made aware with a flag, like errno=1 and errmsg=”String overflow occured”. We need a macro INTEGER that will shorten “long long”, and a macro NUMBER that will make “double” more understandable, the same as the old BASIC type. And we need a macro STRING that will replace “char*”, the same as the old BASIC type as well. Can you help us with all of this? What else do we need? It seems that the #define MACRO approach is the best, most minimal, no external private memory management module, just the “set” accessor function COPY. And we would surely need “get” accessor functions for STRING, NUMBER and INTEGER, like “INTEGER n = GetInteger (array, row, column);”. It could be implemented as a macro as well.
#ifndef CMINUS_ALL_H
#define CMINUS_ALL_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* =========================================================================
1. CORE TYPE ALIASES & CONFIGURATION CONSTANTS
========================================================================= */
#define STRING char*
#define INTEGER long long
#define NUMBER double
#define STR_LEN 255
#define STR_SIZE 256
#ifndef MAX_ROWS
#define MAX_ROWS 64
#endif
#ifndef MAX_COLS
#define MAX_COLS 64
#endif
#define CMINUS_MAGIC 0x4E494D43
/* =========================================================================
2. ENUMERATIONS
========================================================================= */
typedef enum {
EQ, /* Equal (==) */
NE, /* Not Equal (!=) */
LT, /* Less Than (<) */
LE, /* Less Than or Equal (<=) */
GT, /* Greater Than (>) */
GE /* Greater Than or Equal (>=) */
} CompareOp;
typedef enum {
SORT_INT,
SORT_NUM,
SORT_STR
} SortType;
typedef enum {
ASC, /* Ascending */
DESC /* Descending */
} SortOrder;
/* =========================================================================
3. MATRIX STRUCT CONTAINER & GLOBAL STATE
========================================================================= */
typedef struct {
INTEGER rows;
INTEGER cols;
char cells[MAX_ROWS][MAX_COLS][STR_SIZE];
} Matrix;
static int cminus_errno = 0;
static char cminus_errmsg[128] = "";
static char cminus_dummy_cell[STR_SIZE] = "";
/* =========================================================================
4. CORE UTILITIES & BOUNDS CHECKING
========================================================================= */
static inline void cminus_copy(char *dest, const char *src) {
if (!dest || !src) return;
if (strlen(src) > STR_LEN) {
cminus_errno = 1;
strncpy(cminus_errmsg, "String overflow occured", sizeof(cminus_errmsg) - 1);
cminus_errmsg[sizeof(cminus_errmsg) - 1] = '\0';
} else {
cminus_errno = 0;
cminus_errmsg[0] = '\0';
}
strncpy(dest, src, STR_LEN);
dest[STR_LEN] = '\0';
}
#define COPY(dest, src) cminus_copy((dest), (src))
static inline void Matrix_Init(Matrix *m, INTEGER rows, INTEGER cols) {
if (!m) return;
m->rows = (rows > MAX_ROWS) ? MAX_ROWS : ((rows < 1) ? 1 : rows);
m->cols = (cols > MAX_COLS) ? MAX_COLS : ((cols < 1) ? 1 : cols);
memset(m->cells, 0, sizeof(m->cells));
}
#define CLEAR_MATRIX(m_ptr) Matrix_Init((m_ptr), (m_ptr)->rows, (m_ptr)->cols)
static inline int cminus_check_matrix_bounds(const Matrix *m, INTEGER r, INTEGER c) {
if (!m) return 0;
if (r < 0 || r >= m->rows || c < 0 || c >= m->cols) {
cminus_errno = 2;
snprintf(cminus_errmsg, sizeof(cminus_errmsg),
"Matrix out of bounds: accessed [%lld][%lld], active grid size is [%lld][%lld]",
r, c, m->rows - 1, m->cols - 1);
return 0;
}
return 1;
}
/* =========================================================================
5. READ & WRITE ACCESSORS
========================================================================= */
#define GetString(m, r, c) \
(cminus_check_matrix_bounds((m), (r), (c)) ? (m)->cells[r][c] : cminus_dummy_cell)
#define GetInteger(m, r, c) \
(cminus_check_matrix_bounds((m), (r), (c)) ? atoll((m)->cells[r][c]) : 0LL)
#define GetNumber(m, r, c) \
(cminus_check_matrix_bounds((m), (r), (c)) ? atof((m)->cells[r][c]) : 0.0)
#define SetString(m, r, c, str) do { \
if (cminus_check_matrix_bounds((m), (r), (c))) { \
COPY((m)->cells[r][c], (str)); \
} \
} while(0)
#define SetInteger(m, r, c, val) do { \
if (cminus_check_matrix_bounds((m), (r), (c))) { \
snprintf((m)->cells[r][c], STR_SIZE, "%lld", (INTEGER)(val)); \
} \
} while(0)
#define SetNumber(m, r, c, val) do { \
if (cminus_check_matrix_bounds((m), (r), (c))) { \
snprintf((m)->cells[r][c], STR_SIZE, "%.15g", (NUMBER)(val)); \
} \
} while(0)
/* =========================================================================
6. BINARY DISK FILE I/O
========================================================================= */
static inline int Matrix_Save(const Matrix *m, const char *filename) {
if (!m || !filename) { cminus_errno = 3; strncpy(cminus_errmsg, "Null pointer argument", 127); return 0; }
FILE *fp = fopen(filename, "wb");
if (!fp) { cminus_errno = 3; snprintf(cminus_errmsg, 127, "Cannot open '%s'", filename); return 0; }
unsigned int magic = CMINUS_MAGIC;
if (fwrite(&magic, sizeof(unsigned int), 1, fp) != 1 ||
fwrite(&m->rows, sizeof(INTEGER), 1, fp) != 1 ||
fwrite(&m->cols, sizeof(INTEGER), 1, fp) != 1) {
cminus_errno = 4; strncpy(cminus_errmsg, "Header write failed", 127); fclose(fp); return 0;
}
for (INTEGER r = 0; r < m->rows; r++) {
for (INTEGER c = 0; c < m->cols; c++) {
if (fwrite(m->cells[r][c], STR_SIZE, 1, fp) != 1) {
cminus_errno = 4; snprintf(cminus_errmsg, 127, "Write error at [%lld][%lld]", r, c); fclose(fp); return 0;
}
}
}
fclose(fp); cminus_errno = 0; cminus_errmsg[0] = '\0'; return 1;
}
static inline int Matrix_Load(Matrix *m, const char *filename) {
if (!m || !filename) { cminus_errno = 3; strncpy(cminus_errmsg, "Null pointer argument", 127); return 0; }
FILE *fp = fopen(filename, "rb");
if (!fp) { cminus_errno = 3; snprintf(cminus_errmsg, 127, "Cannot open '%s'", filename); return 0; }
unsigned int magic = 0; INTEGER file_rows = 0, file_cols = 0;
if (fread(&magic, sizeof(unsigned int), 1, fp) != 1 || magic != CMINUS_MAGIC ||
fread(&file_rows, sizeof(INTEGER), 1, fp) != 1 || fread(&file_cols, sizeof(INTEGER), 1, fp) != 1) {
cminus_errno = 4; strncpy(cminus_errmsg, "Corrupted binary file", 127); fclose(fp); return 0;
}
if (file_rows < 1 || file_rows > MAX_ROWS || file_cols < 1 || file_cols > MAX_COLS) {
cminus_errno = 4; snprintf(cminus_errmsg, 127, "Grid limits exceeded", MAX_ROWS); fclose(fp); return 0;
}
Matrix_Init(m, file_rows, file_cols);
for (INTEGER r = 0; r < m->rows; r++) {
for (INTEGER c = 0; c < m->cols; c++) {
if (fread(m->cells[r][c], STR_SIZE, 1, fp) != 1) {
cminus_errno = 4; snprintf(cminus_errmsg, 127, "Truncated binary file", MAX_ROWS); fclose(fp); return 0;
}
m->cells[r][c][STR_LEN] = '\0';
}
}
fclose(fp); cminus_errno = 0; cminus_errmsg[0] = '\0'; return 1;
}
#define SAVE_MATRIX(m_ptr, fname) Matrix_Save((m_ptr), (fname))
#define LOAD_MATRIX(m_ptr, fname) Matrix_Load((m_ptr), (fname))
/* =========================================================================
7. CSV PARSING & EXPORT
========================================================================= */
static inline int Matrix_ExportCSV(const Matrix *m, const char *filename) {
if (!m || !filename) return 0;
FILE *fp = fopen(filename, "w");
if (!fp) return 0;
for (INTEGER r = 0; r < m->rows; r++) {
for (INTEGER c = 0; c < m->cols; c++) {
const char *val = m->cells[r][c];
int needs_quotes = 0;
for (const char *p = val; *p; p++) {
if (*p == ',' || *p == '"' || *p == '\n' || *p == '\r') { needs_quotes = 1; break; }
}
if (needs_quotes) {
fputc('"', fp);
for (const char *p = val; *p; p++) { if (*p == '"') fputc('"', fp); fputc(*p, fp); }
fputc('"', fp);
} else { fputs(val, fp); }
if (c < m->cols - 1) fputc(',', fp);
}
fputc('\n', fp);
}
fclose(fp); return 1;
}
static inline int Matrix_ImportCSV(Matrix *m, const char *filename) {
if (!m || !filename) return 0;
FILE *fp = fopen(filename, "r");
if (!fp) return 0;
memset(m->cells, 0, sizeof(m->cells));
INTEGER r = 0, c = 0, max_cols_seen = 0;
char cell_buf[STR_SIZE]; size_t cell_len = 0;
int in_quotes = 0, truncated = 0, ch;
while ((ch = fgetc(fp)) != EOF) {
if (in_quotes) {
if (ch == '"') {
int next_ch = fgetc(fp);
if (next_ch == '"') { if (cell_len < STR_LEN) cell_buf[cell_len++] = '"'; }
else { in_quotes = 0; if (next_ch != EOF) ungetc(next_ch, fp); }
} else { if (cell_len < STR_LEN) cell_buf[cell_len++] = (char)ch; }
} else {
if (ch == '"' && cell_len == 0) { in_quotes = 1; }
else if (ch == ',') {
cell_buf[cell_len] = '\0';
if (r < MAX_ROWS && c < MAX_COLS) COPY(m->cells[r][c], cell_buf);
c++; cell_len = 0;
} else if (ch == '\n' || ch == '\r') {
if (ch == '\r') { int next_ch = fgetc(fp); if (next_ch != '\n' && next_ch != EOF) ungetc(next_ch, fp); }
cell_buf[cell_len] = '\0';
if (r < MAX_ROWS && c < MAX_COLS) COPY(m->cells[r][c], cell_buf);
c++; if (c > max_cols_seen) max_cols_seen = c;
r++; c = 0; cell_len = 0;
if (r >= MAX_ROWS) break;
} else { if (cell_len < STR_LEN) cell_buf[cell_len++] = (char)ch; }
}
}
if (cell_len > 0 || c > 0) {
cell_buf[cell_len] = '\0';
if (r < MAX_ROWS && c < MAX_COLS) COPY(m->cells[r][c], cell_buf);
c++; if (c > max_cols_seen) max_cols_seen = c; r++;
}
fclose(fp);
m->rows = (r > MAX_ROWS) ? MAX_ROWS : r;
m->cols = (max_cols_seen > MAX_COLS) ? MAX_COLS : max_cols_seen;
return 1;
}
#define EXPORT_CSV(m_ptr, fname) Matrix_ExportCSV((m_ptr), (fname))
#define IMPORT_CSV(m_ptr, fname) Matrix_ImportCSV((m_ptr), (fname))
/* =========================================================================
8. ROW FILTERING
========================================================================= */
static inline INTEGER Matrix_FilterByString(const Matrix *src, Matrix *dest, INTEGER col, const char *pattern, int exact) {
if (!src || !dest || !pattern || col < 0 || col >= src->cols) return 0;
Matrix_Init(dest, 0, src->cols); INTEGER match_count = 0;
for (INTEGER r = 0; r < src->rows; r++) {
const char *cell_val = GetString((Matrix*)src, r, col);
int is_match = exact ? (strcmp(cell_val, pattern) == 0) : (strstr(cell_val, pattern) != NULL);
if (is_match) {
if (match_count < MAX_ROWS) {
for (INTEGER c = 0; c < src->cols; c++) COPY(dest->cells[match_count][c], src->cells[r][c]);
match_count++;
} else break;
}
}
dest->rows = match_count; return match_count;
}
static inline INTEGER Matrix_FilterByInteger(const Matrix *src, Matrix *dest, INTEGER col, CompareOp op, INTEGER target) {
if (!src || !dest || col < 0 || col >= src->cols) return 0;
Matrix_Init(dest, 0, src->cols); INTEGER match_count = 0;
for (INTEGER r = 0; r < src->rows; r++) {
INTEGER val = GetInteger((Matrix*)src, r, col); int is_match = 0;
switch (op) {
case EQ: is_match = (val == target); break; case NE: is_match = (val != target); break;
case LT: is_match = (val < target); break; case LE: is_match = (val <= target); break;
case GT: is_match = (val > target); break; case GE: is_match = (val >= target); break;
}
if (is_match) {
if (match_count < MAX_ROWS) {
for (INTEGER c = 0; c < src->cols; c++) COPY(dest->cells[match_count][c], src->cells[r][c]);
match_count++;
} else break;
}
}
dest->rows = match_count; return match_count;
}
#define FILTER_STR_EXACT(src_ptr, dest_ptr, col, pattern) Matrix_FilterByString((src_ptr), (dest_ptr), (col), (pattern), 1)
#define FILTER_STR_CONTAINS(src_ptr, dest_ptr, col, pattern) Matrix_FilterByString((src_ptr), (dest_ptr), (col), (pattern), 0)
#define FILTER_INT(src_ptr, dest_ptr, col, op, target) Matrix_FilterByInteger((src_ptr), (dest_ptr), (col), (op), (target))
/* =========================================================================
9. SELECTION SORTING
========================================================================= */
static inline void cminus_swap_rows(Matrix *m, INTEGER r1, INTEGER r2) {
if (r1 == r2) return;
char temp[STR_SIZE];
for (INTEGER c = 0; c < m->cols; c++) {
memcpy(temp, m->cells[r1][c], STR_SIZE);
memcpy(m->cells[r1][c], m->cells[r2][c], STR_SIZE);
memcpy(m->cells[r2][c], temp, STR_SIZE);
}
}
static inline int cminus_compare_cells(const Matrix *m, INTEGER r1, INTEGER r2, INTEGER col, SortType type) {
if (type == SORT_INT) { INTEGER v1 = atoll(m->cells[r1][col]), v2 = atoll(m->cells[r2][col]); return (v1 > v2) - (v1 < v2); }
else if (type == SORT_NUM) { NUMBER v1 = atof(m->cells[r1][col]), v2 = atof(m->cells[r2][col]); return (v1 > v2) - (v1 < v2); }
else return strcmp(m->cells[r1][col], m->cells[r2][col]);
}
static inline int Matrix_Sort(Matrix *m, INTEGER col, SortType type, SortOrder order) {
if (!m || col < 0 || col >= m->cols || m->rows <= 1) return 0;
for (INTEGER i = 0; i < m->rows - 1; i++) {
INTEGER target_idx = i;
for (INTEGER j = i + 1; j < m->rows; j++) {
int cmp = cminus_compare_cells(m, j, target_idx, col, type);
if ((order == ASC && cmp < 0) || (order == DESC && cmp > 0)) target_idx = j;
}
if (target_idx != i) cminus_swap_rows(m, i, target_idx);
}
return 1;
}
#define SORT_MATRIX_INT(m_ptr, col, order) Matrix_Sort((m_ptr), (col), SORT_INT, (order))
#define SORT_MATRIX_NUM(m_ptr, col, order) Matrix_Sort((m_ptr), (col), SORT_NUM, (order))
#define SORT_MATRIX_STR(m_ptr, col, order) Matrix_Sort((m_ptr), (col), SORT_STR, (order))
/* =========================================================================
10. O(log N) BINARY SEARCH
========================================================================= */
static inline INTEGER Matrix_BinarySearch(const Matrix *m, INTEGER col, SortType type, SortOrder order, const void *key_ptr) {
if (!m || !key_ptr || col < 0 || col >= m->cols || m->rows <= 0) return -1;
INTEGER low = 0, high = m->rows - 1;
while (low <= high) {
INTEGER mid = low + (high - low) / 2; int cmp = 0;
if (type == SORT_INT) {
INTEGER mid_val = atoll(m->cells[mid][col]), target = *(const INTEGER*)key_ptr;
cmp = (mid_val > target) - (mid_val < target);
} else if (type == SORT_NUM) {
NUMBER mid_val = atof(m->cells[mid][col]), target = *(const NUMBER*)key_ptr;
cmp = (mid_val > target) - (mid_val < target);
} else {
cmp = strcmp(m->cells[mid][col], (const char*)key_ptr);
}
if (cmp == 0) return mid;
if (order == ASC) { if (cmp < 0) low = mid + 1; else high = mid - 1; }
else { if (cmp > 0) low = mid + 1; else high = mid - 1; }
}
return -1;
}
#define BSEARCH_MATRIX_INT(m_ptr, col, target, order) Matrix_BinarySearch((m_ptr), (col), SORT_INT, (order), &(INTEGER){target})
#define BSEARCH_MATRIX_NUM(m_ptr, col, target, order) Matrix_BinarySearch((m_ptr), (col), SORT_NUM, (order), &(NUMBER){target})
#define BSEARCH_MATRIX_STR(m_ptr, col, target, order) Matrix_BinarySearch((m_ptr), (col), SORT_STR, (order), (target))
/* =========================================================================
11. RELATIONAL INNER JOIN
========================================================================= */
static inline INTEGER Matrix_InnerJoin(const Matrix *left, INTEGER left_col, const Matrix *right, INTEGER right_col, Matrix *dest, SortType key_type) {
if (!left || !right || !dest) return 0;
INTEGER total_cols = (left->cols + right->cols > MAX_COLS) ? MAX_COLS : (left->cols + right->cols);
Matrix_Init(dest, 0, total_cols); INTEGER match_count = 0;
for (INTEGER r_l = 0; r_l < left->rows; r_l++) {
const char *l_key = left->cells[r_l][left_col];
for (INTEGER r_r = 0; r_r < right->rows; r_r++) {
const char *r_key = right->cells[r_r][right_col];
int match = (key_type == SORT_INT) ? (atoll(l_key) == atoll(r_key)) :
(key_type == SORT_NUM) ? (atof(l_key) == atof(r_key)) : (strcmp(l_key, r_key) == 0);
if (match) {
if (match_count < MAX_ROWS) {
for (INTEGER c = 0; c < left->cols; c++) COPY(dest->cells[match_count][c], left->cells[r_l][c]);
for (INTEGER c = 0; c < right->cols && (left->cols + c) < MAX_COLS; c++) COPY(dest->cells[match_count][left->cols + c], right->cells[r_r][c]);
match_count++;
} else break;
}
}
}
dest->rows = match_count; return match_count;
}
#define INNER_JOIN(left_ptr, l_col, right_ptr, r_col, dest_ptr, key_type) Matrix_InnerJoin((left_ptr), (l_col), (right_ptr), (r_col), (dest_ptr), (key_type))
/* =========================================================================
12. GROUP BY AGGREGATION
========================================================================= */
static inline INTEGER Matrix_GroupBy(const Matrix *src, INTEGER group_col, INTEGER agg_col, Matrix *dest, SortType key_type) {
if (!src || !dest) return 0;
Matrix_Init(dest, 0, 4);
for (INTEGER r = 0; r < src->rows; r++) {
const char *current_key = src->cells[r][group_col];
NUMBER val = GetNumber((Matrix*)src, r, agg_col); INTEGER found_idx = -1;
for (INTEGER g = 0; g < dest->rows; g++) {
const char *ex_key = dest->cells[g][0];
int match = (key_type == SORT_INT) ? (atoll(ex_key) == atoll(current_key)) :
(key_type == SORT_NUM) ? (atof(ex_key) == atof(current_key)) : (strcmp(ex_key, current_key) == 0);
if (match) { found_idx = g; break; }
}
if (found_idx != -1) {
INTEGER count = GetInteger(dest, found_idx, 1) + 1;
NUMBER sum = GetNumber(dest, found_idx, 2) + val;
SetInteger(dest, found_idx, 1, count);
SetNumber(dest, found_idx, 2, sum);
SetNumber(dest, found_idx, 3, sum / (NUMBER)count);
} else {
if (dest->rows < MAX_ROWS) {
INTEGER nr = dest->rows;
SetString(dest, nr, 0, current_key); SetInteger(dest, nr, 1, 1);
SetNumber(dest, nr, 2, val); SetNumber(dest, nr, 3, val);
dest->rows++;
} else break;
}
}
return dest->rows;
}
#define GROUP_BY(src_ptr, group_col, agg_col, dest_ptr, key_type) Matrix_GroupBy((src_ptr), (group_col), (agg_col), (dest_ptr), (key_type))
#endif /* CMINUS_ALL_H */
#include "cminus_all.h"
int main(void) {
Matrix data;
Matrix_Init(&data, 4, 3);
/* Populate Matrix */
SetInteger(&data, 0, 0, 201); SetString(&data, 0, 1, "Hardware"); SetNumber(&data, 0, 2, 450.0);
SetInteger(&data, 1, 0, 105); SetString(&data, 1, 1, "Software"); SetNumber(&data, 1, 2, 1200.0);
SetInteger(&data, 2, 0, 102); SetString(&data, 2, 1, "Hardware"); SetNumber(&data, 2, 2, 350.0);
SetInteger(&data, 3, 0, 304); SetString(&data, 3, 1, "Software"); SetNumber(&data, 3, 2, 950.0);
/* 1. Sort by ID (Col 0, Ascending) */
SORT_MATRIX_INT(&data, 0, ASC);
/* 2. Binary Search for ID 105 */
INTEGER row_idx = BSEARCH_MATRIX_INT(&data, 0, 105, ASC);
if (row_idx != -1) {
printf("Found ID 105 at Row %lld: Dept=%s, Amount=%.2f\n",
row_idx, GetString(&data, row_idx, 1), GetNumber(&data, row_idx, 2));
}
/* 3. GROUP BY Department (Col 1) Aggregating Amount (Col 2) */
Matrix summary;
GROUP_BY(&data, 1, 2, &summary, SORT_STR);
printf("\n--- Department Summary ---\n");
for (INTEGER r = 0; r < summary.rows; r++) {
printf("Dept: %-10s Count: %-2lld Total: %-8.2f Avg: %.2f\n",
GetString(&summary, r, 0), GetInteger(&summary, r, 1),
GetNumber(&summary, r, 2), GetNumber(&summary, r, 3));
}
/* 4. Export Result to CSV */
EXPORT_CSV(&summary, "department_summary.csv");
return 0;
}