Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <string.h>
- #include <stdlib.h>
- #include <time.h>
- //#define _countof(a) (sizeof(a)/sizeof(*(a)))
- #define DoBenchmark
- #ifdef DoBenchmark
- #define _Benchmark while (abs(clock()-ttime)<CLOCKS_PER_SEC)
- #else
- #define _Benchmark
- #endif
- typedef struct {
- int group;
- const char* rule;
- const char* ldraw_output;
- } Rule;
- #include "table.c"
- const Rule* ruleIdx[_countof(rules)];
- //comparator function for qsort
- int CompareRules( const void* pA , const void* pB ) {
- return strcmp( (*((const Rule**)pA))->rule , (*((const Rule**)pB))->rule );
- }
- void InitRules() {
- //set ptrs for each rules element at initial index
- for (int N=0 ; N<_countof(ruleIdx) ; N++ ) { ruleIdx[N] = &rules[N]; }
- qsort( ruleIdx , _countof(ruleIdx) , sizeof(void*) , CompareRules );
- printf("%i rules\n",_countof(ruleIdx));
- }
- const Rule* FindRule( char* pzRule ) {
- int iBegin = 0 , iEnd = _countof(ruleIdx);
- while (iEnd >= iBegin) {
- //try item from middle
- int idx = (iBegin+iEnd)/2;
- const char* pzEntry = ruleIdx[idx]->rule;
- int iResu = strcmp( pzRule , pzEntry );
- if (!iResu) { return ruleIdx[idx]; } //found
- if (iBegin == iEnd) { return NULL; } //NOT found
- //remove the wrong half of possibilities
- if (iResu>0) { iBegin= idx+1; } else { iEnd = idx-1; }
- }
- return NULL; //NOT found
- }
- void NormalizeInput( char* pzInput ) {
- char WasSpace=1, *pOut = pzInput, C;
- while ((C=*pzInput++)) {
- switch (C) {
- case ' ' : case '\t' : case '\r' : case '\n' :
- if (!WasSpace) { *pOut++ = ' '; }
- WasSpace=1; break;
- default:
- *pOut++ = C; WasSpace=0;
- }
- }
- while (pOut[-1]==' ') { pOut--; }
- *pOut = '\0';
- }
- int main() {
- InitRules();
- FILE *outputFile = fopen("output.txt", "a"); // Open the file in append mode
- while (1) {
- char userInput[100];
- printf("Enter a string (or 'exit' to quit): ");
- fgets(userInput, 100, stdin);
- userInput[strcspn(userInput, "\n")] = '\0';
- NormalizeInput( userInput );
- printf("'%s'\n",userInput);
- if (strcmp(userInput, "exit") == 0) {
- break; // Exit the loop if the user types 'exit'
- }
- #ifdef DoBenchmark
- clock_t ttime = clock();
- #endif
- long long iCount = 0;
- const Rule* pFound = NULL;
- #if 1
- _Benchmark {
- pFound = FindRule( userInput );
- iCount++;
- }
- #else
- _Benchmark {
- for (int N=0 ; N<_countof(rules) ; N++) {
- if (!strcmp(userInput , rules[N].rule)) {
- pFound = &rules[N]; break;
- }
- }
- iCount++;
- }
- #endif
- if (pFound) {
- printf("%s\n", pFound->ldraw_output);
- fprintf(outputFile, "%s\n", pFound->ldraw_output);
- } else {
- printf("No match found.\n");
- }
- #ifdef DoBenchmark
- printf("took %.05fms %lli/s\n",1000.0/iCount,iCount);
- #endif
- }
- fclose(outputFile); // Close the file
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement