Four is the number of letters in the ...: Difference between revisions
Four is the number of letters in the ... (view source)
Revision as of 17:14, 13 June 2020
, 3 years agoC - reduce memory usage
(Performance improvement) |
(C - reduce memory usage) |
||
Line 136:
}
▲typedef struct string_tag {
size_t size;
size_t capacity;
} string_buffer;
} str;▼
void
s->capacity = capacity;▼
memcpy(s->str.buffer, str, len + 1);▼
s->size = len;▼
}
void
buffer->string = NULL;
▲ free(s->str.ptr);
}
void string_buffer_clear(string_buffer* buffer) {
void string_append(string_t* s, const char* str) {▼
}▼
size_t min_capacity = len + s->size + 1;▼
void string_buffer_append(string_buffer* buffer, const char* str, size_t len) {
size_t new_capacity = 2 * s->capacity;▼
if (new_capacity < min_capacity)
new_capacity = min_capacity;
}
s->size += len;▼
}
typedef struct word_tag {
size_t offset;
▲}
} word;
}▼
typedef struct word_list_tag {
size_t size;
size_t capacity;
} word_list;
Line 206 ⟶ 187:
words->size = 0;
words->capacity = capacity;
words->words = xmalloc(capacity * sizeof(
string_buffer_create(&words->str, capacity*8);
}
void word_list_destroy(word_list* words) {
string_destroy(&words->words[i]);▼
free(words->words);
words->words = NULL;
Line 219 ⟶ 200:
void word_list_clear(word_list* words) {
words->size = 0;
}
size_t offset = words->str.size;
size_t len = strlen(str);
string_buffer_append(&words->str, str, len);
size_t min_capacity = words->size + 1;
if (words->capacity < min_capacity) {
size_t new_capacity = (words->capacity *
if (new_capacity < min_capacity)
new_capacity = min_capacity;
words->words = xrealloc(words->words, new_capacity * sizeof(
words->capacity = new_capacity;
}
▲}
word* w = &words->words[words->size - 1];
size_t len = strlen(str);
string_buffer_append(&words->str, str, len);
}
Line 247 ⟶ 237:
word_list_append(words, get_small_name(&tens[n/10 - 2], ordinal));
} else {
}
count = 1;
Line 268 ⟶ 258:
}
size_t count_letters(const
size_t letters = 0;
const char* s =
for (size_t i = 0, n =
if (isalpha((unsigned char)s[i]))
++letters;
Line 288 ⟶ 279:
word_list_append(result, words[i]);
for (size_t i = 1; count > n; ++i) {
n += append_number_name(result, count_letters(
word_list_append(result, "in");
word_list_append(result, "the");
Line 294 ⟶ 285:
n += append_number_name(result, i + 1, true);
// Append a comma to the final word
}
}
Line 302 ⟶ 293:
if (n == 0)
return 0;
▲ return length;
}
Line 318 ⟶ 306:
if (i != 0)
printf("%c", i % 25 == 0 ? '\n' : ' ');
printf("%'2lu", count_letters(&result
}
printf("\nSentence length: %'lu\n", sentence_length(&result));
for (n = 1000; n <= 10000000; n *= 10) {
sentence(&result, n);
const
const char* s = result.str.string + w->offset;
printf("The %'luth word is '%.*s' and has %lu letters. ", n,
count_letters(
printf("Sentence length: %'lu\n" , sentence_length(&result));
}
|