mirror of
https://github.com/kuhyx/testsAndMisc-archive.git
synced 2026-07-04 15:43:11 +02:00
feat: great beautiful fixes
This commit is contained in:
parent
aae75807a2
commit
67da5c4fb9
@ -9,11 +9,11 @@
|
|||||||
* ./vocabulary_curve test.txt 50
|
* ./vocabulary_curve test.txt 50
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
#include <ctype.h>
|
||||||
|
#include <stdbool.h>
|
||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
#include <string.h>
|
#include <string.h>
|
||||||
#include <ctype.h>
|
|
||||||
#include <stdbool.h>
|
|
||||||
|
|
||||||
#define MAX_WORD_LEN 64
|
#define MAX_WORD_LEN 64
|
||||||
#define MAX_WORDS 500000
|
#define MAX_WORDS 500000
|
||||||
@ -21,7 +21,8 @@
|
|||||||
#define HASH_SIZE 200003 /* Prime number for better distribution */
|
#define HASH_SIZE 200003 /* Prime number for better distribution */
|
||||||
|
|
||||||
/* Word entry for hash table */
|
/* Word entry for hash table */
|
||||||
typedef struct WordEntry {
|
typedef struct WordEntry
|
||||||
|
{
|
||||||
char word[MAX_WORD_LEN];
|
char word[MAX_WORD_LEN];
|
||||||
int count;
|
int count;
|
||||||
int rank; /* 1-indexed rank by frequency (1 = most common) */
|
int rank; /* 1-indexed rank by frequency (1 = most common) */
|
||||||
@ -38,42 +39,50 @@ static WordEntry *word_sequence[MAX_WORDS];
|
|||||||
static int num_words = 0;
|
static int num_words = 0;
|
||||||
|
|
||||||
/* Result for each excerpt length */
|
/* Result for each excerpt length */
|
||||||
typedef struct {
|
typedef struct
|
||||||
|
{
|
||||||
int excerpt_length;
|
int excerpt_length;
|
||||||
int min_vocab_needed;
|
int min_vocab_needed;
|
||||||
int start_pos; /* Start position in word_sequence */
|
int start_pos; /* Start position in word_sequence */
|
||||||
} ExcerptResult;
|
} ExcerptResult;
|
||||||
|
|
||||||
/* Simple hash function */
|
/* Simple hash function */
|
||||||
static unsigned int hash_word(const char *word) {
|
static unsigned int hash_word(const char *word)
|
||||||
|
{
|
||||||
unsigned int hash = 5381;
|
unsigned int hash = 5381;
|
||||||
int c;
|
int c;
|
||||||
while ((c = *word++)) {
|
while ((c = *word++))
|
||||||
|
{
|
||||||
hash = ((hash << 5) + hash) + c;
|
hash = ((hash << 5) + hash) + c;
|
||||||
}
|
}
|
||||||
return hash % HASH_SIZE;
|
return hash % HASH_SIZE;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Find or create word entry */
|
/* Find or create word entry */
|
||||||
static WordEntry *get_or_create_word(const char *word) {
|
static WordEntry *get_or_create_word(const char *word)
|
||||||
|
{
|
||||||
unsigned int h = hash_word(word);
|
unsigned int h = hash_word(word);
|
||||||
WordEntry *entry = hash_table[h];
|
WordEntry *entry = hash_table[h];
|
||||||
|
|
||||||
while (entry) {
|
while (entry)
|
||||||
if (strcmp(entry->word, word) == 0) {
|
{
|
||||||
|
if (strcmp(entry->word, word) == 0)
|
||||||
|
{
|
||||||
return entry;
|
return entry;
|
||||||
}
|
}
|
||||||
entry = entry->next;
|
entry = entry->next;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Create new entry */
|
/* Create new entry */
|
||||||
if (num_unique_words >= MAX_UNIQUE_WORDS) {
|
if (num_unique_words >= MAX_UNIQUE_WORDS)
|
||||||
|
{
|
||||||
fprintf(stderr, "Too many unique words\n");
|
fprintf(stderr, "Too many unique words\n");
|
||||||
exit(1);
|
exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
entry = malloc(sizeof(WordEntry));
|
entry = malloc(sizeof(WordEntry));
|
||||||
if (!entry) {
|
if (!entry)
|
||||||
|
{
|
||||||
fprintf(stderr, "Memory allocation failed\n");
|
fprintf(stderr, "Memory allocation failed\n");
|
||||||
exit(1);
|
exit(1);
|
||||||
}
|
}
|
||||||
@ -91,21 +100,22 @@ static WordEntry *get_or_create_word(const char *word) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* Compare function for sorting by frequency (descending) */
|
/* Compare function for sorting by frequency (descending) */
|
||||||
static int compare_by_count(const void *a, const void *b) {
|
static int compare_by_count(const void *a, const void *b)
|
||||||
|
{
|
||||||
const WordEntry *wa = *(const WordEntry **)a;
|
const WordEntry *wa = *(const WordEntry **)a;
|
||||||
const WordEntry *wb = *(const WordEntry **)b;
|
const WordEntry *wb = *(const WordEntry **)b;
|
||||||
return wb->count - wa->count; /* Descending */
|
return wb->count - wa->count; /* Descending */
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Check if character is part of a word */
|
/* Check if character is part of a word */
|
||||||
static bool is_word_char(int c) {
|
static bool is_word_char(int c) { return isalnum(c) || c == '_' || (unsigned char)c >= 128; }
|
||||||
return isalnum(c) || c == '_' || (unsigned char)c >= 128;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Read and process file */
|
/* Read and process file */
|
||||||
static bool process_file(const char *filename) {
|
static bool process_file(const char *filename)
|
||||||
|
{
|
||||||
FILE *fp = fopen(filename, "r");
|
FILE *fp = fopen(filename, "r");
|
||||||
if (!fp) {
|
if (!fp)
|
||||||
|
{
|
||||||
fprintf(stderr, "Cannot open file: %s\n", filename);
|
fprintf(stderr, "Cannot open file: %s\n", filename);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@ -114,18 +124,24 @@ static bool process_file(const char *filename) {
|
|||||||
int word_len = 0;
|
int word_len = 0;
|
||||||
int c;
|
int c;
|
||||||
|
|
||||||
while ((c = fgetc(fp)) != EOF) {
|
while ((c = fgetc(fp)) != EOF)
|
||||||
if (is_word_char(c)) {
|
{
|
||||||
if (word_len < MAX_WORD_LEN - 1) {
|
if (is_word_char(c))
|
||||||
|
{
|
||||||
|
if (word_len < MAX_WORD_LEN - 1)
|
||||||
|
{
|
||||||
word[word_len++] = tolower(c);
|
word[word_len++] = tolower(c);
|
||||||
}
|
}
|
||||||
} else if (word_len > 0) {
|
}
|
||||||
|
else if (word_len > 0)
|
||||||
|
{
|
||||||
word[word_len] = '\0';
|
word[word_len] = '\0';
|
||||||
|
|
||||||
WordEntry *entry = get_or_create_word(word);
|
WordEntry *entry = get_or_create_word(word);
|
||||||
entry->count++;
|
entry->count++;
|
||||||
|
|
||||||
if (num_words >= MAX_WORDS) {
|
if (num_words >= MAX_WORDS)
|
||||||
|
{
|
||||||
fprintf(stderr, "Too many words in file\n");
|
fprintf(stderr, "Too many words in file\n");
|
||||||
fclose(fp);
|
fclose(fp);
|
||||||
return false;
|
return false;
|
||||||
@ -139,12 +155,14 @@ static bool process_file(const char *filename) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* Handle last word if file doesn't end with whitespace */
|
/* Handle last word if file doesn't end with whitespace */
|
||||||
if (word_len > 0) {
|
if (word_len > 0)
|
||||||
|
{
|
||||||
word[word_len] = '\0';
|
word[word_len] = '\0';
|
||||||
WordEntry *entry = get_or_create_word(word);
|
WordEntry *entry = get_or_create_word(word);
|
||||||
entry->count++;
|
entry->count++;
|
||||||
|
|
||||||
if (num_words < MAX_WORDS) {
|
if (num_words < MAX_WORDS)
|
||||||
|
{
|
||||||
word_sequence[num_words++] = entry;
|
word_sequence[num_words++] = entry;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -154,7 +172,8 @@ static bool process_file(const char *filename) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* Assign ranks based on frequency */
|
/* Assign ranks based on frequency */
|
||||||
static void assign_ranks(void) {
|
static void assign_ranks(void)
|
||||||
|
{
|
||||||
/* Sort all_entries by frequency (this doesn't affect word_sequence) */
|
/* Sort all_entries by frequency (this doesn't affect word_sequence) */
|
||||||
qsort(all_entries, num_unique_words, sizeof(WordEntry *), compare_by_count);
|
qsort(all_entries, num_unique_words, sizeof(WordEntry *), compare_by_count);
|
||||||
|
|
||||||
@ -162,13 +181,19 @@ static void assign_ranks(void) {
|
|||||||
* Words with same frequency get same rank.
|
* Words with same frequency get same rank.
|
||||||
* Next rank is current_position + 1 (skipping numbers).
|
* Next rank is current_position + 1 (skipping numbers).
|
||||||
* Example: counts 5,3,3,2 -> ranks 1,2,2,4 (not 1,2,3,4) */
|
* Example: counts 5,3,3,2 -> ranks 1,2,2,4 (not 1,2,3,4) */
|
||||||
for (int i = 0; i < num_unique_words; i++) {
|
for (int i = 0; i < num_unique_words; i++)
|
||||||
if (i == 0) {
|
{
|
||||||
|
if (i == 0)
|
||||||
|
{
|
||||||
all_entries[i]->rank = 1;
|
all_entries[i]->rank = 1;
|
||||||
} else if (all_entries[i]->count == all_entries[i-1]->count) {
|
}
|
||||||
|
else if (all_entries[i]->count == all_entries[i - 1]->count)
|
||||||
|
{
|
||||||
/* Same frequency as previous word - same rank */
|
/* Same frequency as previous word - same rank */
|
||||||
all_entries[i]->rank = all_entries[i-1]->rank;
|
all_entries[i]->rank = all_entries[i - 1]->rank;
|
||||||
} else {
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
/* Different frequency - rank is position + 1 */
|
/* Different frequency - rank is position + 1 */
|
||||||
all_entries[i]->rank = i + 1;
|
all_entries[i]->rank = i + 1;
|
||||||
}
|
}
|
||||||
@ -176,7 +201,8 @@ static void assign_ranks(void) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* Analyze excerpt and return max rank needed */
|
/* Analyze excerpt and return max rank needed */
|
||||||
static int analyze_excerpt(int start, int length) {
|
static int analyze_excerpt(int start, int length)
|
||||||
|
{
|
||||||
/* Track which entries we've seen using a simple visited array */
|
/* Track which entries we've seen using a simple visited array */
|
||||||
/* We use the rank field is already assigned, so we can check uniqueness */
|
/* We use the rank field is already assigned, so we can check uniqueness */
|
||||||
static bool seen_rank[MAX_UNIQUE_WORDS + 1];
|
static bool seen_rank[MAX_UNIQUE_WORDS + 1];
|
||||||
@ -184,13 +210,16 @@ static int analyze_excerpt(int start, int length) {
|
|||||||
|
|
||||||
int max_rank = 0;
|
int max_rank = 0;
|
||||||
|
|
||||||
for (int i = start; i < start + length; i++) {
|
for (int i = start; i < start + length; i++)
|
||||||
|
{
|
||||||
WordEntry *entry = word_sequence[i];
|
WordEntry *entry = word_sequence[i];
|
||||||
int rank = entry->rank;
|
int rank = entry->rank;
|
||||||
|
|
||||||
if (!seen_rank[rank]) {
|
if (!seen_rank[rank])
|
||||||
|
{
|
||||||
seen_rank[rank] = true;
|
seen_rank[rank] = true;
|
||||||
if (rank > max_rank) {
|
if (rank > max_rank)
|
||||||
|
{
|
||||||
max_rank = rank;
|
max_rank = rank;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -200,16 +229,20 @@ static int analyze_excerpt(int start, int length) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* Find optimal excerpts for each length */
|
/* Find optimal excerpts for each length */
|
||||||
static void find_optimal_excerpts(int max_length, ExcerptResult *results) {
|
static void find_optimal_excerpts(int max_length, ExcerptResult *results)
|
||||||
for (int length = 1; length <= max_length && length <= num_words; length++) {
|
{
|
||||||
|
for (int length = 1; length <= max_length && length <= num_words; length++)
|
||||||
|
{
|
||||||
int best_vocab = num_unique_words + 1;
|
int best_vocab = num_unique_words + 1;
|
||||||
int best_start = 0;
|
int best_start = 0;
|
||||||
|
|
||||||
/* Slide window through text */
|
/* Slide window through text */
|
||||||
for (int start = 0; start <= num_words - length; start++) {
|
for (int start = 0; start <= num_words - length; start++)
|
||||||
|
{
|
||||||
int vocab_needed = analyze_excerpt(start, length);
|
int vocab_needed = analyze_excerpt(start, length);
|
||||||
|
|
||||||
if (vocab_needed < best_vocab) {
|
if (vocab_needed < best_vocab)
|
||||||
|
{
|
||||||
best_vocab = vocab_needed;
|
best_vocab = vocab_needed;
|
||||||
best_start = start;
|
best_start = start;
|
||||||
}
|
}
|
||||||
@ -222,33 +255,42 @@ static void find_optimal_excerpts(int max_length, ExcerptResult *results) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* Print excerpt words */
|
/* Print excerpt words */
|
||||||
static void print_excerpt(int start, int length) {
|
static void print_excerpt(int start, int length)
|
||||||
for (int i = start; i < start + length; i++) {
|
{
|
||||||
if (i > start) printf(" ");
|
for (int i = start; i < start + length; i++)
|
||||||
|
{
|
||||||
|
if (i > start)
|
||||||
|
printf(" ");
|
||||||
printf("%s", word_sequence[i]->word);
|
printf("%s", word_sequence[i]->word);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Print words needed (sorted by rank) */
|
/* Print words needed (sorted by rank) */
|
||||||
static void print_words_needed(int start, int length) {
|
static void print_words_needed(int start, int length)
|
||||||
|
{
|
||||||
/* Collect unique entries */
|
/* Collect unique entries */
|
||||||
static WordEntry *unique_entries[MAX_UNIQUE_WORDS];
|
static WordEntry *unique_entries[MAX_UNIQUE_WORDS];
|
||||||
static bool seen_rank[MAX_UNIQUE_WORDS + 1];
|
static bool seen_rank[MAX_UNIQUE_WORDS + 1];
|
||||||
memset(seen_rank, 0, (num_unique_words + 1) * sizeof(bool));
|
memset(seen_rank, 0, (num_unique_words + 1) * sizeof(bool));
|
||||||
|
|
||||||
int count = 0;
|
int count = 0;
|
||||||
for (int i = start; i < start + length; i++) {
|
for (int i = start; i < start + length; i++)
|
||||||
|
{
|
||||||
WordEntry *entry = word_sequence[i];
|
WordEntry *entry = word_sequence[i];
|
||||||
if (!seen_rank[entry->rank]) {
|
if (!seen_rank[entry->rank])
|
||||||
|
{
|
||||||
seen_rank[entry->rank] = true;
|
seen_rank[entry->rank] = true;
|
||||||
unique_entries[count++] = entry;
|
unique_entries[count++] = entry;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Sort by rank (simple bubble sort - small arrays) */
|
/* Sort by rank (simple bubble sort - small arrays) */
|
||||||
for (int i = 0; i < count - 1; i++) {
|
for (int i = 0; i < count - 1; i++)
|
||||||
for (int j = i + 1; j < count; j++) {
|
{
|
||||||
if (unique_entries[i]->rank > unique_entries[j]->rank) {
|
for (int j = i + 1; j < count; j++)
|
||||||
|
{
|
||||||
|
if (unique_entries[i]->rank > unique_entries[j]->rank)
|
||||||
|
{
|
||||||
WordEntry *tmp = unique_entries[i];
|
WordEntry *tmp = unique_entries[i];
|
||||||
unique_entries[i] = unique_entries[j];
|
unique_entries[i] = unique_entries[j];
|
||||||
unique_entries[j] = tmp;
|
unique_entries[j] = tmp;
|
||||||
@ -257,14 +299,17 @@ static void print_words_needed(int start, int length) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* Print */
|
/* Print */
|
||||||
for (int i = 0; i < count; i++) {
|
for (int i = 0; i < count; i++)
|
||||||
if (i > 0) printf(", ");
|
{
|
||||||
|
if (i > 0)
|
||||||
|
printf(", ");
|
||||||
printf("%s(#%d)", unique_entries[i]->word, unique_entries[i]->rank);
|
printf("%s(#%d)", unique_entries[i]->word, unique_entries[i]->rank);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Print results */
|
/* Print results */
|
||||||
static void print_results(ExcerptResult *results, int max_length) {
|
static void print_results(ExcerptResult *results, int max_length)
|
||||||
|
{
|
||||||
printf("======================================================================\n");
|
printf("======================================================================\n");
|
||||||
printf("VOCABULARY LEARNING CURVE\n");
|
printf("VOCABULARY LEARNING CURVE\n");
|
||||||
printf("======================================================================\n");
|
printf("======================================================================\n");
|
||||||
@ -279,13 +324,16 @@ static void print_results(ExcerptResult *results, int max_length) {
|
|||||||
|
|
||||||
int prev_vocab = 0;
|
int prev_vocab = 0;
|
||||||
int actual_max = max_length;
|
int actual_max = max_length;
|
||||||
if (actual_max > num_words) actual_max = num_words;
|
if (actual_max > num_words)
|
||||||
|
actual_max = num_words;
|
||||||
|
|
||||||
for (int i = 0; i < actual_max; i++) {
|
for (int i = 0; i < actual_max; i++)
|
||||||
|
{
|
||||||
ExcerptResult *r = &results[i];
|
ExcerptResult *r = &results[i];
|
||||||
|
|
||||||
printf("\n[Length %d] Vocab needed: %d", r->excerpt_length, r->min_vocab_needed);
|
printf("\n[Length %d] Vocab needed: %d", r->excerpt_length, r->min_vocab_needed);
|
||||||
if (r->min_vocab_needed > prev_vocab) {
|
if (r->min_vocab_needed > prev_vocab)
|
||||||
|
{
|
||||||
printf(" (+%d)", r->min_vocab_needed - prev_vocab);
|
printf(" (+%d)", r->min_vocab_needed - prev_vocab);
|
||||||
}
|
}
|
||||||
printf("\n");
|
printf("\n");
|
||||||
@ -303,7 +351,8 @@ static void print_results(ExcerptResult *results, int max_length) {
|
|||||||
|
|
||||||
printf("\n----------------------------------------------------------------------\n");
|
printf("\n----------------------------------------------------------------------\n");
|
||||||
|
|
||||||
if (actual_max > 0) {
|
if (actual_max > 0)
|
||||||
|
{
|
||||||
ExcerptResult *final = &results[actual_max - 1];
|
ExcerptResult *final = &results[actual_max - 1];
|
||||||
printf("\nTo understand a %d-word excerpt,\n", final->excerpt_length);
|
printf("\nTo understand a %d-word excerpt,\n", final->excerpt_length);
|
||||||
printf("you need to learn at minimum %d top words.\n", final->min_vocab_needed);
|
printf("you need to learn at minimum %d top words.\n", final->min_vocab_needed);
|
||||||
@ -311,17 +360,22 @@ static void print_results(ExcerptResult *results, int max_length) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* Free memory */
|
/* Free memory */
|
||||||
static void cleanup(void) {
|
static void cleanup(void)
|
||||||
for (int i = 0; i < num_unique_words; i++) {
|
{
|
||||||
|
for (int i = 0; i < num_unique_words; i++)
|
||||||
|
{
|
||||||
free(all_entries[i]);
|
free(all_entries[i]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Dump all vocabulary with ranks (for Python integration) */
|
/* Dump all vocabulary with ranks (for Python integration) */
|
||||||
static void dump_vocabulary(int max_rank) {
|
static void dump_vocabulary(int max_rank)
|
||||||
|
{
|
||||||
printf("VOCAB_DUMP_START\n");
|
printf("VOCAB_DUMP_START\n");
|
||||||
for (int i = 0; i < num_unique_words; i++) {
|
for (int i = 0; i < num_unique_words; i++)
|
||||||
if (all_entries[i]->rank <= max_rank) {
|
{
|
||||||
|
if (all_entries[i]->rank <= max_rank)
|
||||||
|
{
|
||||||
printf("%s;%d\n", all_entries[i]->word, all_entries[i]->rank);
|
printf("%s;%d\n", all_entries[i]->word, all_entries[i]->rank);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -329,20 +383,26 @@ static void dump_vocabulary(int max_rank) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* Find longest excerpt using only top N words (inverse mode) */
|
/* Find longest excerpt using only top N words (inverse mode) */
|
||||||
static void find_longest_excerpt(int max_vocab) {
|
static void find_longest_excerpt(int max_vocab)
|
||||||
|
{
|
||||||
/* Sliding window: find longest contiguous sequence where all words have rank <= max_vocab */
|
/* Sliding window: find longest contiguous sequence where all words have rank <= max_vocab */
|
||||||
int best_start = 0;
|
int best_start = 0;
|
||||||
int best_length = 0;
|
int best_length = 0;
|
||||||
|
|
||||||
int left = 0;
|
int left = 0;
|
||||||
for (int right = 0; right < num_words; right++) {
|
for (int right = 0; right < num_words; right++)
|
||||||
|
{
|
||||||
/* If current word is outside our vocabulary, move left past it */
|
/* If current word is outside our vocabulary, move left past it */
|
||||||
if (word_sequence[right]->rank > max_vocab) {
|
if (word_sequence[right]->rank > max_vocab)
|
||||||
|
{
|
||||||
left = right + 1;
|
left = right + 1;
|
||||||
} else {
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
/* Current window [left, right] is valid */
|
/* Current window [left, right] is valid */
|
||||||
int length = right - left + 1;
|
int length = right - left + 1;
|
||||||
if (length > best_length) {
|
if (length > best_length)
|
||||||
|
{
|
||||||
best_length = length;
|
best_length = length;
|
||||||
best_start = left;
|
best_start = left;
|
||||||
}
|
}
|
||||||
@ -361,10 +421,13 @@ static void find_longest_excerpt(int max_vocab) {
|
|||||||
printf("----------------------------------------------------------------------\n");
|
printf("----------------------------------------------------------------------\n");
|
||||||
printf("\n");
|
printf("\n");
|
||||||
|
|
||||||
if (best_length == 0) {
|
if (best_length == 0)
|
||||||
|
{
|
||||||
printf("No valid excerpt found with top %d words.\n", max_vocab);
|
printf("No valid excerpt found with top %d words.\n", max_vocab);
|
||||||
printf("The text may require rarer words from the very beginning.\n");
|
printf("The text may require rarer words from the very beginning.\n");
|
||||||
} else {
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
printf("LONGEST EXCERPT: %d words\n", best_length);
|
printf("LONGEST EXCERPT: %d words\n", best_length);
|
||||||
printf("Position: words %d to %d\n", best_start + 1, best_start + best_length);
|
printf("Position: words %d to %d\n", best_start + 1, best_start + best_length);
|
||||||
printf("\n");
|
printf("\n");
|
||||||
@ -376,8 +439,10 @@ static void find_longest_excerpt(int max_vocab) {
|
|||||||
/* Find the rarest word in the excerpt */
|
/* Find the rarest word in the excerpt */
|
||||||
int max_rank_used = 0;
|
int max_rank_used = 0;
|
||||||
const char *rarest_word = NULL;
|
const char *rarest_word = NULL;
|
||||||
for (int i = best_start; i < best_start + best_length; i++) {
|
for (int i = best_start; i < best_start + best_length; i++)
|
||||||
if (word_sequence[i]->rank > max_rank_used) {
|
{
|
||||||
|
if (word_sequence[i]->rank > max_rank_used)
|
||||||
|
{
|
||||||
max_rank_used = word_sequence[i]->rank;
|
max_rank_used = word_sequence[i]->rank;
|
||||||
rarest_word = word_sequence[i]->word;
|
rarest_word = word_sequence[i]->word;
|
||||||
}
|
}
|
||||||
@ -388,8 +453,10 @@ static void find_longest_excerpt(int max_vocab) {
|
|||||||
static bool seen_rank[MAX_UNIQUE_WORDS + 1];
|
static bool seen_rank[MAX_UNIQUE_WORDS + 1];
|
||||||
memset(seen_rank, 0, (num_unique_words + 1) * sizeof(bool));
|
memset(seen_rank, 0, (num_unique_words + 1) * sizeof(bool));
|
||||||
int unique_count = 0;
|
int unique_count = 0;
|
||||||
for (int i = best_start; i < best_start + best_length; i++) {
|
for (int i = best_start; i < best_start + best_length; i++)
|
||||||
if (!seen_rank[word_sequence[i]->rank]) {
|
{
|
||||||
|
if (!seen_rank[word_sequence[i]->rank])
|
||||||
|
{
|
||||||
seen_rank[word_sequence[i]->rank] = true;
|
seen_rank[word_sequence[i]->rank] = true;
|
||||||
unique_count++;
|
unique_count++;
|
||||||
}
|
}
|
||||||
@ -400,18 +467,23 @@ static void find_longest_excerpt(int max_vocab) {
|
|||||||
printf("\n----------------------------------------------------------------------\n");
|
printf("\n----------------------------------------------------------------------\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
int main(int argc, char *argv[]) {
|
int main(int argc, char *argv[])
|
||||||
if (argc < 2) {
|
{
|
||||||
|
if (argc < 2)
|
||||||
|
{
|
||||||
fprintf(stderr, "Usage: %s <file.txt> [options]\n", argv[0]);
|
fprintf(stderr, "Usage: %s <file.txt> [options]\n", argv[0]);
|
||||||
fprintf(stderr, "\nModes:\n");
|
fprintf(stderr, "\nModes:\n");
|
||||||
fprintf(stderr, " (default) Find minimum vocab needed for each excerpt length\n");
|
fprintf(stderr, " (default) Find minimum vocab needed for each excerpt length\n");
|
||||||
fprintf(stderr, " --max-vocab N INVERSE: Find longest excerpt using only top N words\n");
|
fprintf(stderr,
|
||||||
|
" --max-vocab N INVERSE: Find longest excerpt using only top N words\n");
|
||||||
fprintf(stderr, "\nOptions:\n");
|
fprintf(stderr, "\nOptions:\n");
|
||||||
fprintf(stderr, " max_length Maximum excerpt length to analyze (default: 30)\n");
|
fprintf(stderr, " max_length Maximum excerpt length to analyze (default: 30)\n");
|
||||||
fprintf(stderr, " --dump-vocab [N] Output all words with ranks up to N\n");
|
fprintf(stderr, " --dump-vocab [N] Output all words with ranks up to N\n");
|
||||||
fprintf(stderr, "\nExamples:\n");
|
fprintf(stderr, "\nExamples:\n");
|
||||||
fprintf(stderr, " %s book.txt 50 # Analyze excerpts up to 50 words\n", argv[0]);
|
fprintf(stderr, " %s book.txt 50 # Analyze excerpts up to 50 words\n",
|
||||||
fprintf(stderr, " %s book.txt --max-vocab 500 # Find longest excerpt with top 500 words\n", argv[0]);
|
argv[0]);
|
||||||
|
fprintf(stderr, " %s book.txt --max-vocab 500 # Find longest excerpt with top 500 words\n",
|
||||||
|
argv[0]);
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -422,27 +494,40 @@ int main(int argc, char *argv[]) {
|
|||||||
int max_vocab_mode = 0; /* 0 = normal mode, >0 = inverse mode with this vocab limit */
|
int max_vocab_mode = 0; /* 0 = normal mode, >0 = inverse mode with this vocab limit */
|
||||||
|
|
||||||
/* Parse arguments */
|
/* Parse arguments */
|
||||||
for (int i = 2; i < argc; i++) {
|
for (int i = 2; i < argc; i++)
|
||||||
if (strcmp(argv[i], "--dump-vocab") == 0) {
|
{
|
||||||
|
if (strcmp(argv[i], "--dump-vocab") == 0)
|
||||||
|
{
|
||||||
dump_vocab = true;
|
dump_vocab = true;
|
||||||
if (i + 1 < argc && argv[i + 1][0] != '-') {
|
if (i + 1 < argc && argv[i + 1][0] != '-')
|
||||||
|
{
|
||||||
dump_max_rank = atoi(argv[++i]);
|
dump_max_rank = atoi(argv[++i]);
|
||||||
}
|
}
|
||||||
} else if (strcmp(argv[i], "--max-vocab") == 0) {
|
}
|
||||||
if (i + 1 < argc) {
|
else if (strcmp(argv[i], "--max-vocab") == 0)
|
||||||
|
{
|
||||||
|
if (i + 1 < argc)
|
||||||
|
{
|
||||||
max_vocab_mode = atoi(argv[++i]);
|
max_vocab_mode = atoi(argv[++i]);
|
||||||
if (max_vocab_mode < 1) {
|
if (max_vocab_mode < 1)
|
||||||
|
{
|
||||||
fprintf(stderr, "Error: --max-vocab requires a positive number\n");
|
fprintf(stderr, "Error: --max-vocab requires a positive number\n");
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
} else {
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
fprintf(stderr, "Error: --max-vocab requires a number\n");
|
fprintf(stderr, "Error: --max-vocab requires a number\n");
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
} else if (argv[i][0] != '-') {
|
}
|
||||||
|
else if (argv[i][0] != '-')
|
||||||
|
{
|
||||||
max_length = atoi(argv[i]);
|
max_length = atoi(argv[i]);
|
||||||
if (max_length < 1) max_length = 1;
|
if (max_length < 1)
|
||||||
if (max_length > 1000) max_length = 1000;
|
max_length = 1;
|
||||||
|
if (max_length > 1000)
|
||||||
|
max_length = 1000;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -450,11 +535,13 @@ int main(int argc, char *argv[]) {
|
|||||||
memset(hash_table, 0, sizeof(hash_table));
|
memset(hash_table, 0, sizeof(hash_table));
|
||||||
|
|
||||||
/* Process file */
|
/* Process file */
|
||||||
if (!process_file(filename)) {
|
if (!process_file(filename))
|
||||||
|
{
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (num_words == 0) {
|
if (num_words == 0)
|
||||||
|
{
|
||||||
fprintf(stderr, "No words found in file\n");
|
fprintf(stderr, "No words found in file\n");
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
@ -463,12 +550,15 @@ int main(int argc, char *argv[]) {
|
|||||||
assign_ranks();
|
assign_ranks();
|
||||||
|
|
||||||
/* Inverse mode: find longest excerpt with limited vocabulary */
|
/* Inverse mode: find longest excerpt with limited vocabulary */
|
||||||
if (max_vocab_mode > 0) {
|
if (max_vocab_mode > 0)
|
||||||
|
{
|
||||||
find_longest_excerpt(max_vocab_mode);
|
find_longest_excerpt(max_vocab_mode);
|
||||||
|
|
||||||
/* Dump vocabulary if requested */
|
/* Dump vocabulary if requested */
|
||||||
if (dump_vocab) {
|
if (dump_vocab)
|
||||||
if (dump_max_rank == 0) dump_max_rank = max_vocab_mode;
|
{
|
||||||
|
if (dump_max_rank == 0)
|
||||||
|
dump_max_rank = max_vocab_mode;
|
||||||
dump_vocabulary(dump_max_rank);
|
dump_vocabulary(dump_max_rank);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -478,7 +568,8 @@ int main(int argc, char *argv[]) {
|
|||||||
|
|
||||||
/* Normal mode: find optimal excerpts */
|
/* Normal mode: find optimal excerpts */
|
||||||
ExcerptResult *results = malloc(max_length * sizeof(ExcerptResult));
|
ExcerptResult *results = malloc(max_length * sizeof(ExcerptResult));
|
||||||
if (!results) {
|
if (!results)
|
||||||
|
{
|
||||||
fprintf(stderr, "Memory allocation failed\n");
|
fprintf(stderr, "Memory allocation failed\n");
|
||||||
cleanup();
|
cleanup();
|
||||||
return 1;
|
return 1;
|
||||||
@ -490,12 +581,15 @@ int main(int argc, char *argv[]) {
|
|||||||
print_results(results, max_length);
|
print_results(results, max_length);
|
||||||
|
|
||||||
/* Dump vocabulary if requested */
|
/* Dump vocabulary if requested */
|
||||||
if (dump_vocab) {
|
if (dump_vocab)
|
||||||
|
{
|
||||||
/* If no max_rank specified, use the max from the excerpt */
|
/* If no max_rank specified, use the max from the excerpt */
|
||||||
if (dump_max_rank == 0 && max_length > 0) {
|
if (dump_max_rank == 0 && max_length > 0)
|
||||||
|
{
|
||||||
dump_max_rank = results[max_length - 1].min_vocab_needed;
|
dump_max_rank = results[max_length - 1].min_vocab_needed;
|
||||||
}
|
}
|
||||||
if (dump_max_rank > 0) {
|
if (dump_max_rank > 0)
|
||||||
|
{
|
||||||
dump_vocabulary(dump_max_rank);
|
dump_vocabulary(dump_max_rank);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,25 +1,24 @@
|
|||||||
#include <math.h>
|
|
||||||
#include <iostream>
|
|
||||||
#include <iomanip>
|
#include <iomanip>
|
||||||
|
#include <iostream>
|
||||||
|
#include <math.h>
|
||||||
|
|
||||||
const unsigned long long int ITERATIONS = 10000;
|
const unsigned long long int ITERATIONS = 10000;
|
||||||
|
|
||||||
long double getPi()
|
long double getPi() {
|
||||||
{
|
|
||||||
long double pi = 4;
|
long double pi = 4;
|
||||||
bool negative = 1;
|
bool negative = 1;
|
||||||
for(unsigned int i = 3; i < ITERATIONS; i += 2)
|
for (unsigned int i = 3; i < ITERATIONS; i += 2) {
|
||||||
{
|
if (negative)
|
||||||
if(negative) pi -= 4.0 / i;
|
pi -= 4.0 / i;
|
||||||
else pi += 4.0 / i;
|
else
|
||||||
|
pi += 4.0 / i;
|
||||||
negative = !negative;
|
negative = !negative;
|
||||||
}
|
}
|
||||||
std::cout << std::setprecision(2000) << pi << std::endl;
|
std::cout << std::setprecision(2000) << pi << std::endl;
|
||||||
return pi;
|
return pi;
|
||||||
}
|
}
|
||||||
|
|
||||||
int main()
|
int main() {
|
||||||
{
|
|
||||||
getPi();
|
getPi();
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,11 +1,12 @@
|
|||||||
#include <iostream>
|
#include <iostream>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
const std::vector <std::string> ATUTY = {"BA", "Trefl", "Karo", "Kier", "Pik"};
|
const std::vector<std::string> ATUTY = {"BA", "Trefl", "Karo", "Kier", "Pik"};
|
||||||
const bool A_ID = 0;
|
const bool A_ID = 0;
|
||||||
const bool B_ID = 1;
|
const bool B_ID = 1;
|
||||||
const std::vector <std::string> GRACZE = {};
|
const std::vector<std::string> GRACZE = {};
|
||||||
const std::vector <std::string> PO_PARTII {"Nikt", GRACZE[A_ID], GRACZE[B_ID], "Obaj Gracze"};
|
const std::vector<std::string> PO_PARTII{"Nikt", GRACZE[A_ID], GRACZE[B_ID],
|
||||||
|
"Obaj Gracze"};
|
||||||
const int DOMYSLNE_LEWY = 6;
|
const int DOMYSLNE_LEWY = 6;
|
||||||
const int BEZ_ATUTU_ID = 1;
|
const int BEZ_ATUTU_ID = 1;
|
||||||
const int TREFL_ID = 2;
|
const int TREFL_ID = 2;
|
||||||
@ -19,70 +20,61 @@ const int MAKSYMALNY_LEW = 7;
|
|||||||
const int MINIMALNY_LEW = 1;
|
const int MINIMALNY_LEW = 1;
|
||||||
const int ILOSC_LEW = 13;
|
const int ILOSC_LEW = 13;
|
||||||
|
|
||||||
void print(const std::string s)
|
void print(const std::string s) { std::cout << s << std::endl; }
|
||||||
{
|
|
||||||
std::cout << s << std::endl;
|
|
||||||
}
|
|
||||||
|
|
||||||
void tabela(std::vector <int> punktyA, std::vector <int> punktyB)
|
void tabela(std::vector<int> punktyA, std::vector<int> punktyB) {
|
||||||
{
|
|
||||||
|
|
||||||
std::cout << "Numer Gry" << " Po Partii" << " " << GRACZE[A_ID] << " " << GRACZE[B_ID] << std::endl;
|
std::cout << "Numer Gry" << " Po Partii" << " " << GRACZE[A_ID]
|
||||||
for(int i = 0; i < punktyA.size(); i++)
|
<< " " << GRACZE[B_ID] << std::endl;
|
||||||
{
|
for (int i = 0; i < punktyA.size(); i++) {
|
||||||
|
|
||||||
std::cout << i + 1 << " " << PO_PARTII[i % CYKL_PO_PARTII] << " " << punktyA[i] << " " << punktyB[i] << std::endl;
|
std::cout << i + 1 << " " << PO_PARTII[i % CYKL_PO_PARTII]
|
||||||
|
<< " " << punktyA[i] << " "
|
||||||
|
<< punktyB[i] << std::endl;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void lwyAtut(int lwy, int atut)
|
void lwyAtut(int lwy, int atut) {
|
||||||
{
|
if (lwy == SZLEMIK) {
|
||||||
if(lwy == SZLEMIK)
|
|
||||||
{
|
|
||||||
print("Wybrano szlemik!");
|
print("Wybrano szlemik!");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if(lwy == SZLEM)
|
if (lwy == SZLEM) {
|
||||||
{
|
|
||||||
print("Wybrano szlema!");
|
print("Wybrano szlema!");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
std::cout << "Wybrano kontrakt: " << lwy << " " << ATUTY[atut - 1] << std::endl;
|
std::cout << "Wybrano kontrakt: " << lwy << " " << ATUTY[atut - 1]
|
||||||
|
<< std::endl;
|
||||||
}
|
}
|
||||||
|
|
||||||
int zagraneLwy()
|
int zagraneLwy() {
|
||||||
{
|
|
||||||
int lwy;
|
int lwy;
|
||||||
bool flagaLwy;
|
bool flagaLwy;
|
||||||
do
|
do {
|
||||||
{
|
|
||||||
flagaLwy = 0;
|
flagaLwy = 0;
|
||||||
print("Ile lew?");
|
print("Ile lew?");
|
||||||
char lwyC;
|
char lwyC;
|
||||||
std::cin >> lwyC;
|
std::cin >> lwyC;
|
||||||
lwy = lwyC - '0';
|
lwy = lwyC - '0';
|
||||||
if(lwy < MINIMALNY_LEW)
|
if (lwy < MINIMALNY_LEW) {
|
||||||
{
|
|
||||||
print("Podales za malo lew!");
|
print("Podales za malo lew!");
|
||||||
flagaLwy = 1;
|
flagaLwy = 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
if(lwy > MAKSYMALNY_LEW)
|
if (lwy > MAKSYMALNY_LEW) {
|
||||||
{
|
|
||||||
print("Podales za duzo lew!");
|
print("Podales za duzo lew!");
|
||||||
flagaLwy = 1;
|
flagaLwy = 1;
|
||||||
}
|
}
|
||||||
}while(flagaLwy);
|
} while (flagaLwy);
|
||||||
return lwy;
|
return lwy;
|
||||||
}
|
}
|
||||||
|
|
||||||
int zagranyAtut(int lwy)
|
int zagranyAtut(int lwy) {
|
||||||
{
|
|
||||||
int atut;
|
int atut;
|
||||||
bool flagaAtut;
|
bool flagaAtut;
|
||||||
if(lwy > 6) return 1;
|
if (lwy > 6)
|
||||||
do
|
return 1;
|
||||||
{
|
do {
|
||||||
flagaAtut = 0;
|
flagaAtut = 0;
|
||||||
print("Jaki atut?");
|
print("Jaki atut?");
|
||||||
print("1 - BA");
|
print("1 - BA");
|
||||||
@ -93,17 +85,15 @@ int zagranyAtut(int lwy)
|
|||||||
char atutC;
|
char atutC;
|
||||||
std::cin >> atutC;
|
std::cin >> atutC;
|
||||||
atut = atutC - '0';
|
atut = atutC - '0';
|
||||||
if(atut < 1 || atut > 5)
|
if (atut < 1 || atut > 5) {
|
||||||
{
|
|
||||||
print("Wybrales zla liczbe!");
|
print("Wybrales zla liczbe!");
|
||||||
flagaAtut = 1;
|
flagaAtut = 1;
|
||||||
}
|
}
|
||||||
}while(flagaAtut);
|
} while (flagaAtut);
|
||||||
return atut;
|
return atut;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool zagranaKontra()
|
bool zagranaKontra() {
|
||||||
{
|
|
||||||
char kontraC = '0';
|
char kontraC = '0';
|
||||||
print("Czy zostala zagrana kontra?");
|
print("Czy zostala zagrana kontra?");
|
||||||
print("1 - TAK");
|
print("1 - TAK");
|
||||||
@ -113,8 +103,7 @@ bool zagranaKontra()
|
|||||||
return kontraBool;
|
return kontraBool;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool zagranaRekontra()
|
bool zagranaRekontra() {
|
||||||
{
|
|
||||||
char rekontraC = '0';
|
char rekontraC = '0';
|
||||||
print("Czy zostala zagrana rekontra?");
|
print("Czy zostala zagrana rekontra?");
|
||||||
print("1 - TAK");
|
print("1 - TAK");
|
||||||
@ -124,20 +113,20 @@ bool zagranaRekontra()
|
|||||||
return rekontraBool;
|
return rekontraBool;
|
||||||
}
|
}
|
||||||
|
|
||||||
void stanGry(int lwy, int atut, bool kontraBool, bool rekontraBool, int ktoraGra, int ktoKontrakt)
|
void stanGry(int lwy, int atut, bool kontraBool, bool rekontraBool,
|
||||||
{
|
int ktoraGra, int ktoKontrakt) {
|
||||||
std::cout << "Kontrakt Wygrali: " << GRACZE[ktoKontrakt] << std::endl;
|
std::cout << "Kontrakt Wygrali: " << GRACZE[ktoKontrakt] << std::endl;
|
||||||
lwyAtut(lwy, atut);
|
lwyAtut(lwy, atut);
|
||||||
if(kontraBool)
|
if (kontraBool) {
|
||||||
{
|
if (rekontraBool)
|
||||||
if(rekontraBool) print("Zostala zagrana REkontra!");
|
print("Zostala zagrana REkontra!");
|
||||||
else print("Zostala zagrana Kontra!");
|
else
|
||||||
|
print("Zostala zagrana Kontra!");
|
||||||
}
|
}
|
||||||
std::cout << "Po partii sa: " << PO_PARTII[ktoraGra % 4] << std::endl;
|
std::cout << "Po partii sa: " << PO_PARTII[ktoraGra % 4] << std::endl;
|
||||||
}
|
}
|
||||||
|
|
||||||
int ktoKontrakt()
|
int ktoKontrakt() {
|
||||||
{
|
|
||||||
char ktoKontraktC;
|
char ktoKontraktC;
|
||||||
print("Kto wygral Kontrakt?");
|
print("Kto wygral Kontrakt?");
|
||||||
std::cout << "1. " << GRACZE[A_ID] << std::endl;
|
std::cout << "1. " << GRACZE[A_ID] << std::endl;
|
||||||
@ -148,8 +137,7 @@ int ktoKontrakt()
|
|||||||
return ktoKontraktI;
|
return ktoKontraktI;
|
||||||
}
|
}
|
||||||
|
|
||||||
int ileWpadek()
|
int ileWpadek() {
|
||||||
{
|
|
||||||
std::string ileWpadekS;
|
std::string ileWpadekS;
|
||||||
print("ile lew wygrali obroncy?");
|
print("ile lew wygrali obroncy?");
|
||||||
std::cin >> ileWpadekS;
|
std::cin >> ileWpadekS;
|
||||||
@ -157,229 +145,218 @@ int ileWpadek()
|
|||||||
return ileWpadek;
|
return ileWpadek;
|
||||||
}
|
}
|
||||||
|
|
||||||
void punkty(std::vector <int> &punktyA, std::vector <int> &punktyB, int lwy, int atut, bool kontraBool, bool rekontraBool,
|
void punkty(std::vector<int> &punktyA, std::vector<int> &punktyB, int lwy,
|
||||||
int ktoraGra, int ktoKontraktI, bool rozgrywajacyWygral, int wpadki)
|
int atut, bool kontraBool, bool rekontraBool, int ktoraGra,
|
||||||
{
|
int ktoKontraktI, bool rozgrywajacyWygral, int wpadki) {
|
||||||
int sumaPunktow = 0;
|
int sumaPunktow = 0;
|
||||||
if(rozgrywajacyWygral)
|
if (rozgrywajacyWygral) {
|
||||||
{
|
|
||||||
int zdobyteLewy = ILOSC_LEW - wpadki - DOMYSLNE_LEWY;
|
int zdobyteLewy = ILOSC_LEW - wpadki - DOMYSLNE_LEWY;
|
||||||
int nadrobki = zdobyteLewy - lwy;
|
int nadrobki = zdobyteLewy - lwy;
|
||||||
int punktyZaLew;
|
int punktyZaLew;
|
||||||
std::cout << "wartosc kontraBool: " << kontraBool << "; wartosc rekontraBool: " << rekontraBool << std::endl;
|
std::cout << "wartosc kontraBool: " << kontraBool
|
||||||
|
<< "; wartosc rekontraBool: " << rekontraBool << std::endl;
|
||||||
|
|
||||||
// Lewy Deklarowane
|
// Lewy Deklarowane
|
||||||
if(atut == TREFL_ID || atut == KARO_ID)
|
if (atut == TREFL_ID || atut == KARO_ID) {
|
||||||
{
|
|
||||||
print("kontrakt TREFL lub KARO kazda karta kontraktowa za 20");
|
print("kontrakt TREFL lub KARO kazda karta kontraktowa za 20");
|
||||||
punktyZaLew = 20;
|
punktyZaLew = 20;
|
||||||
if(kontraBool)
|
if (kontraBool) {
|
||||||
{
|
|
||||||
print("kontra TREFL lub KARO, kazda karta kontraktowa za 40");
|
print("kontra TREFL lub KARO, kazda karta kontraktowa za 40");
|
||||||
punktyZaLew = 40;
|
punktyZaLew = 40;
|
||||||
}
|
}
|
||||||
if(rekontraBool)
|
if (rekontraBool) {
|
||||||
{
|
|
||||||
print("rekontra TREFL lub KARO, kazda karta kontraktowa za 80");
|
print("rekontra TREFL lub KARO, kazda karta kontraktowa za 80");
|
||||||
punktyZaLew = 80;
|
punktyZaLew = 80;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::cout << "Ilosc lew w kontrakcie: " << lwy << " do punktow dodaje sie " << lwy * punktyZaLew << std::endl;
|
std::cout << "Ilosc lew w kontrakcie: " << lwy
|
||||||
|
<< " do punktow dodaje sie " << lwy * punktyZaLew << std::endl;
|
||||||
sumaPunktow += (lwy * punktyZaLew);
|
sumaPunktow += (lwy * punktyZaLew);
|
||||||
}
|
}
|
||||||
|
|
||||||
if(atut == KIER_ID || atut == PIK_ID)
|
if (atut == KIER_ID || atut == PIK_ID) {
|
||||||
{
|
|
||||||
print("kontrakt KIER lub PIK, kazda kontraktowa 30");
|
print("kontrakt KIER lub PIK, kazda kontraktowa 30");
|
||||||
punktyZaLew = 30;
|
punktyZaLew = 30;
|
||||||
if(kontraBool)
|
if (kontraBool) {
|
||||||
{
|
|
||||||
print("kontra KIER lub PIK, kazda kontraktowa za 60");
|
print("kontra KIER lub PIK, kazda kontraktowa za 60");
|
||||||
punktyZaLew = 60;
|
punktyZaLew = 60;
|
||||||
}
|
}
|
||||||
if(rekontraBool)
|
if (rekontraBool) {
|
||||||
{
|
|
||||||
print("rekontra KIER lub PIK, kazda kontraktowa za 120");
|
print("rekontra KIER lub PIK, kazda kontraktowa za 120");
|
||||||
punktyZaLew = 120;
|
punktyZaLew = 120;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::cout << "Ilosc lew w kontrakcie: " << lwy << " do punktow dodaje sie " << lwy * punktyZaLew << std::endl;
|
std::cout << "Ilosc lew w kontrakcie: " << lwy
|
||||||
|
<< " do punktow dodaje sie " << lwy * punktyZaLew << std::endl;
|
||||||
sumaPunktow += (lwy * punktyZaLew);
|
sumaPunktow += (lwy * punktyZaLew);
|
||||||
}
|
}
|
||||||
|
|
||||||
if(atut == BEZ_ATUTU_ID)
|
if (atut == BEZ_ATUTU_ID) {
|
||||||
{
|
|
||||||
punktyZaLew = 30;
|
punktyZaLew = 30;
|
||||||
print("kontrakt BEZ_ATUTU, pierwsza lewa za 40, kazda nastepna za 30");
|
print("kontrakt BEZ_ATUTU, pierwsza lewa za 40, kazda nastepna za 30");
|
||||||
sumaPunktow = 40;
|
sumaPunktow = 40;
|
||||||
if(kontraBool)
|
if (kontraBool) {
|
||||||
{
|
|
||||||
print("kontrakt BEZ_ATUTU, pierwsza lewa za 80, kazda nastepna za 60");
|
print("kontrakt BEZ_ATUTU, pierwsza lewa za 80, kazda nastepna za 60");
|
||||||
sumaPunktow = 80;
|
sumaPunktow = 80;
|
||||||
punktyZaLew = 60;
|
punktyZaLew = 60;
|
||||||
}
|
}
|
||||||
if(rekontraBool)
|
if (rekontraBool) {
|
||||||
{
|
print(
|
||||||
print("kontrakt BEZ_ATUTU, pierwsza lewa za 160, kazda nastepna za 120");
|
"kontrakt BEZ_ATUTU, pierwsza lewa za 160, kazda nastepna za 120");
|
||||||
sumaPunktow = 160;
|
sumaPunktow = 160;
|
||||||
punktyZaLew = 120;
|
punktyZaLew = 120;
|
||||||
}
|
}
|
||||||
sumaPunktow += ( (lwy - 1) * punktyZaLew);
|
sumaPunktow += ((lwy - 1) * punktyZaLew);
|
||||||
}
|
}
|
||||||
|
|
||||||
bool czyRozgrywajacyPoPartii = ( ( (ktoraGra % CYKL_PO_PARTII) - 1) == ktoKontraktI || ktoraGra % CYKL_PO_PARTII == 3);
|
bool czyRozgrywajacyPoPartii =
|
||||||
|
(((ktoraGra % CYKL_PO_PARTII) - 1) == ktoKontraktI ||
|
||||||
|
ktoraGra % CYKL_PO_PARTII == 3);
|
||||||
|
|
||||||
if(lwy == SZLEMIK)
|
if (lwy == SZLEMIK) {
|
||||||
{
|
if (czyRozgrywajacyPoPartii)
|
||||||
if(czyRozgrywajacyPoPartii) sumaPunktow += 750;
|
sumaPunktow += 750;
|
||||||
else sumaPunktow += 500;
|
else
|
||||||
|
sumaPunktow += 500;
|
||||||
}
|
}
|
||||||
|
|
||||||
if(lwy == SZLEM)
|
if (lwy == SZLEM) {
|
||||||
{
|
if (czyRozgrywajacyPoPartii)
|
||||||
if(czyRozgrywajacyPoPartii) sumaPunktow += 1500;
|
sumaPunktow += 1500;
|
||||||
else sumaPunktow += 1000;
|
else
|
||||||
|
sumaPunktow += 1000;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
bool dograna = (sumaPunktow >= 100);
|
bool dograna = (sumaPunktow >= 100);
|
||||||
if(dograna)
|
if (dograna) {
|
||||||
{
|
if (czyRozgrywajacyPoPartii)
|
||||||
if(czyRozgrywajacyPoPartii) sumaPunktow += 500;
|
sumaPunktow += 500;
|
||||||
else sumaPunktow += 300;
|
else
|
||||||
}else sumaPunktow += 50;
|
sumaPunktow += 300;
|
||||||
|
} else
|
||||||
|
sumaPunktow += 50;
|
||||||
|
|
||||||
// Nadrobki
|
// Nadrobki
|
||||||
|
|
||||||
if(!kontraBool && !rekontraBool)
|
if (!kontraBool && !rekontraBool) {
|
||||||
{
|
|
||||||
int punktyZaNadrobki = punktyZaLew;
|
int punktyZaNadrobki = punktyZaLew;
|
||||||
sumaPunktow += nadrobki * punktyZaNadrobki;
|
sumaPunktow += nadrobki * punktyZaNadrobki;
|
||||||
}
|
}
|
||||||
if(kontraBool && !rekontraBool)
|
if (kontraBool && !rekontraBool) {
|
||||||
{
|
|
||||||
int punktyZaNadrobki = 100;
|
int punktyZaNadrobki = 100;
|
||||||
if(czyRozgrywajacyPoPartii) punktyZaNadrobki = 200;
|
if (czyRozgrywajacyPoPartii)
|
||||||
|
punktyZaNadrobki = 200;
|
||||||
sumaPunktow += nadrobki * punktyZaNadrobki;
|
sumaPunktow += nadrobki * punktyZaNadrobki;
|
||||||
}
|
}
|
||||||
|
|
||||||
if(kontraBool && rekontraBool)
|
if (kontraBool && rekontraBool) {
|
||||||
{
|
|
||||||
|
|
||||||
int punktyZaNadrobki = 200;
|
int punktyZaNadrobki = 200;
|
||||||
if(czyRozgrywajacyPoPartii) punktyZaNadrobki = 400;
|
if (czyRozgrywajacyPoPartii)
|
||||||
|
punktyZaNadrobki = 400;
|
||||||
sumaPunktow += nadrobki * punktyZaNadrobki;
|
sumaPunktow += nadrobki * punktyZaNadrobki;
|
||||||
}
|
}
|
||||||
|
|
||||||
if(kontraBool && !rekontraBool) sumaPunktow += 50;
|
if (kontraBool && !rekontraBool)
|
||||||
|
sumaPunktow += 50;
|
||||||
|
|
||||||
if(kontraBool && rekontraBool) sumaPunktow += 100;
|
if (kontraBool && rekontraBool)
|
||||||
|
sumaPunktow += 100;
|
||||||
std::cout << "Rozgrywajacy zdobyl: " << sumaPunktow << std::endl;
|
std::cout << "Rozgrywajacy zdobyl: " << sumaPunktow << std::endl;
|
||||||
if(ktoKontraktI == A_ID)
|
if (ktoKontraktI == A_ID) {
|
||||||
{
|
|
||||||
punktyA.push_back(sumaPunktow);
|
punktyA.push_back(sumaPunktow);
|
||||||
punktyB.push_back(0);
|
punktyB.push_back(0);
|
||||||
}
|
} else {
|
||||||
else
|
|
||||||
{
|
|
||||||
punktyB.push_back(sumaPunktow);
|
punktyB.push_back(sumaPunktow);
|
||||||
punktyA.push_back(0);
|
punktyA.push_back(0);
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}else
|
} else {
|
||||||
{
|
|
||||||
int zebraneLewy = ILOSC_LEW - wpadki;
|
int zebraneLewy = ILOSC_LEW - wpadki;
|
||||||
int lewyWpadkowe = (lwy + DOMYSLNE_LEWY) - zebraneLewy;
|
int lewyWpadkowe = (lwy + DOMYSLNE_LEWY) - zebraneLewy;
|
||||||
int sumaPunktow = 0;
|
int sumaPunktow = 0;
|
||||||
bool broniacyPoPartii = ( ((ktoraGra % CYKL_PO_PARTII) - 1) == !ktoKontraktI || ktoraGra % CYKL_PO_PARTII == 3);
|
bool broniacyPoPartii =
|
||||||
if(broniacyPoPartii)
|
(((ktoraGra % CYKL_PO_PARTII) - 1) == !ktoKontraktI ||
|
||||||
{
|
ktoraGra % CYKL_PO_PARTII == 3);
|
||||||
|
if (broniacyPoPartii) {
|
||||||
|
|
||||||
if(!kontraBool && !rekontraBool)
|
if (!kontraBool && !rekontraBool) {
|
||||||
{
|
|
||||||
sumaPunktow = 100;
|
sumaPunktow = 100;
|
||||||
for(int i = 1; i < lewyWpadkowe; i++)
|
for (int i = 1; i < lewyWpadkowe; i++) {
|
||||||
{
|
if (i < 4)
|
||||||
if(i < 4) sumaPunktow += 100;
|
sumaPunktow += 100;
|
||||||
else sumaPunktow += 0;
|
else
|
||||||
|
sumaPunktow += 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if(kontraBool && !rekontraBool)
|
if (kontraBool && !rekontraBool) {
|
||||||
{
|
|
||||||
sumaPunktow = 200;
|
sumaPunktow = 200;
|
||||||
for(int i = 1; i < lewyWpadkowe; i++)
|
for (int i = 1; i < lewyWpadkowe; i++) {
|
||||||
{
|
if (i < 4)
|
||||||
if(i < 4) sumaPunktow += 300;
|
sumaPunktow += 300;
|
||||||
else sumaPunktow += 0;
|
else
|
||||||
|
sumaPunktow += 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if(kontraBool && rekontraBool)
|
if (kontraBool && rekontraBool) {
|
||||||
{
|
|
||||||
sumaPunktow = 400;
|
sumaPunktow = 400;
|
||||||
for(int i = 1; i < lewyWpadkowe; i++)
|
for (int i = 1; i < lewyWpadkowe; i++) {
|
||||||
{
|
if (i < 4)
|
||||||
if(i < 4) sumaPunktow += 600;
|
sumaPunktow += 600;
|
||||||
else sumaPunktow += 0;
|
else
|
||||||
|
sumaPunktow += 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}else
|
} else {
|
||||||
{
|
if (!kontraBool && !rekontraBool) {
|
||||||
if(!kontraBool && !rekontraBool)
|
|
||||||
{
|
|
||||||
sumaPunktow = 50;
|
sumaPunktow = 50;
|
||||||
for(int i = 1; i < lewyWpadkowe; i++)
|
for (int i = 1; i < lewyWpadkowe; i++) {
|
||||||
{
|
if (i < 4)
|
||||||
if(i < 4) sumaPunktow += 50;
|
sumaPunktow += 50;
|
||||||
else sumaPunktow += 0;
|
else
|
||||||
|
sumaPunktow += 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if(kontraBool && !rekontraBool)
|
if (kontraBool && !rekontraBool) {
|
||||||
{
|
|
||||||
sumaPunktow = 100;
|
sumaPunktow = 100;
|
||||||
for(int i = 1; i < lewyWpadkowe; i++)
|
for (int i = 1; i < lewyWpadkowe; i++) {
|
||||||
{
|
if (i < 4)
|
||||||
if(i < 4) sumaPunktow += 200;
|
sumaPunktow += 200;
|
||||||
else sumaPunktow += 100;
|
else
|
||||||
|
sumaPunktow += 100;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if(kontraBool && rekontraBool)
|
if (kontraBool && rekontraBool) {
|
||||||
{
|
|
||||||
sumaPunktow = 200;
|
sumaPunktow = 200;
|
||||||
for(int i = 1; i < lewyWpadkowe; i++)
|
for (int i = 1; i < lewyWpadkowe; i++) {
|
||||||
{
|
if (i < 4)
|
||||||
if(i < 4) sumaPunktow += 400;
|
sumaPunktow += 400;
|
||||||
else sumaPunktow += 200;
|
else
|
||||||
|
sumaPunktow += 200;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
std::cout << "Broniacy zdobyli: " << sumaPunktow << std::endl;
|
std::cout << "Broniacy zdobyli: " << sumaPunktow << std::endl;
|
||||||
if(ktoKontraktI == A_ID)
|
if (ktoKontraktI == A_ID) {
|
||||||
{
|
|
||||||
punktyB.push_back(sumaPunktow);
|
punktyB.push_back(sumaPunktow);
|
||||||
punktyA.push_back(0);
|
punktyA.push_back(0);
|
||||||
}
|
} else {
|
||||||
else
|
|
||||||
{
|
|
||||||
punktyA.push_back(sumaPunktow);
|
punktyA.push_back(sumaPunktow);
|
||||||
punktyB.push_back(0);
|
punktyB.push_back(0);
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
bool gra() {
|
||||||
bool gra()
|
|
||||||
{
|
|
||||||
bool koniecGry = 0;
|
bool koniecGry = 0;
|
||||||
std::vector <int> punktyA;
|
std::vector<int> punktyA;
|
||||||
std::vector <int> punktyB;
|
std::vector<int> punktyB;
|
||||||
do{
|
do {
|
||||||
int ktoraGra = 0;
|
int ktoraGra = 0;
|
||||||
tabela(punktyA, punktyB);
|
tabela(punktyA, punktyB);
|
||||||
int ktoKontraktI = ktoKontrakt();
|
int ktoKontraktI = ktoKontrakt();
|
||||||
@ -387,24 +364,28 @@ bool gra()
|
|||||||
int atut = zagranyAtut(lwy);
|
int atut = zagranyAtut(lwy);
|
||||||
bool kontraBool = zagranaKontra();
|
bool kontraBool = zagranaKontra();
|
||||||
bool rekontraBool = 0;
|
bool rekontraBool = 0;
|
||||||
if(kontraBool) rekontraBool = zagranaRekontra();
|
if (kontraBool)
|
||||||
|
rekontraBool = zagranaRekontra();
|
||||||
stanGry(lwy, atut, kontraBool, rekontraBool, ktoraGra, ktoKontraktI);
|
stanGry(lwy, atut, kontraBool, rekontraBool, ktoraGra, ktoKontraktI);
|
||||||
int wpadki = ileWpadek();
|
int wpadki = ileWpadek();
|
||||||
int zebraneLewy = ILOSC_LEW - wpadki;
|
int zebraneLewy = ILOSC_LEW - wpadki;
|
||||||
|
|
||||||
bool rozgrywajacyWygral = 1;
|
bool rozgrywajacyWygral = 1;
|
||||||
if( zebraneLewy >= lwy + DOMYSLNE_LEWY) rozgrywajacyWygral = 1;
|
if (zebraneLewy >= lwy + DOMYSLNE_LEWY)
|
||||||
else rozgrywajacyWygral = 0;
|
rozgrywajacyWygral = 1;
|
||||||
punkty(punktyA, punktyB, lwy, atut, kontraBool, rekontraBool, ktoraGra, ktoKontraktI, rozgrywajacyWygral, wpadki);
|
else
|
||||||
|
rozgrywajacyWygral = 0;
|
||||||
|
punkty(punktyA, punktyB, lwy, atut, kontraBool, rekontraBool, ktoraGra,
|
||||||
|
ktoKontraktI, rozgrywajacyWygral, wpadki);
|
||||||
print("Czy koniec gry? 1 - TAK, 0 - NIE");
|
print("Czy koniec gry? 1 - TAK, 0 - NIE");
|
||||||
std::cin >> koniecGry;
|
std::cin >> koniecGry;
|
||||||
}while(!koniecGry);
|
} while (!koniecGry);
|
||||||
tabela(punktyA, punktyB);
|
tabela(punktyA, punktyB);
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
int main()
|
int main() {
|
||||||
{
|
while (gra())
|
||||||
while(gra());
|
;
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,91 +1,72 @@
|
|||||||
#ifndef BASIC_CPP
|
#ifndef BASIC_CPP
|
||||||
#define BASIC_CPP
|
#define BASIC_CPP
|
||||||
|
|
||||||
|
#include <iostream>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
#include <iostream>
|
|
||||||
#include <windows.h>
|
#include <windows.h>
|
||||||
|
|
||||||
void print(const std::string s) { std::cout << s << std::endl; }
|
void print(const std::string s) { std::cout << s << std::endl; }
|
||||||
void printErrorStringContainsNotNumber(const std::string s)
|
void printErrorStringContainsNotNumber(const std::string s) {
|
||||||
{
|
|
||||||
std::cout << "string: \"" << s
|
std::cout << "string: \"" << s
|
||||||
<< "\" contains character different than number " << std::endl;
|
<< "\" contains character different than number " << std::endl;
|
||||||
}
|
}
|
||||||
|
|
||||||
void printNumberTooLow(const int number, const int min)
|
void printNumberTooLow(const int number, const int min) {
|
||||||
{
|
std::cout << "number: " << number << " is too low. Minimal number is: " << min
|
||||||
std::cout << "number: " << number
|
<< std::endl;
|
||||||
<< " is too low. Minimal number is: " << min << std::endl;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void printNumberTooHigh(const int number, const int max)
|
void printNumberTooHigh(const int number, const int max) {
|
||||||
{
|
|
||||||
std::cout << "number: " << number
|
std::cout << "number: " << number
|
||||||
<< " is too high. Maximal number is: " << max << std::endl;
|
<< " is too high. Maximal number is: " << max << std::endl;
|
||||||
}
|
}
|
||||||
|
|
||||||
void printNotValidStringLength(const std::string s, const int desiredLength)
|
void printNotValidStringLength(const std::string s, const int desiredLength) {
|
||||||
{
|
std::cout << "String: \"" << s
|
||||||
std::cout << "String: \"" << s << "\" is too short/too long, it is: "
|
<< "\" is too short/too long, it is: " << s.length()
|
||||||
<< s.length() << " characters long but should be: " << desiredLength
|
<< " characters long but should be: " << desiredLength
|
||||||
<< " characters long " << std::endl;
|
<< " characters long " << std::endl;
|
||||||
}
|
}
|
||||||
|
|
||||||
void printInvalidCharacter(const char c, const char desiredCharacter)
|
void printInvalidCharacter(const char c, const char desiredCharacter) {
|
||||||
{
|
|
||||||
std::cout << "[ " << c << " ] Is invalid character, expected: [ "
|
std::cout << "[ " << c << " ] Is invalid character, expected: [ "
|
||||||
<< desiredCharacter << " ]" << std::endl;
|
<< desiredCharacter << " ]" << std::endl;
|
||||||
}
|
}
|
||||||
|
|
||||||
void printContainsIllegalCharacter( const std::string s,
|
void printContainsIllegalCharacter(const std::string s,
|
||||||
const char illegalCharacter )
|
const char illegalCharacter) {
|
||||||
{
|
|
||||||
std::cout << "String: " << s << " consists of illegal sign: ["
|
std::cout << "String: " << s << " consists of illegal sign: ["
|
||||||
<< illegalCharacter << "]!" << std::endl;
|
<< illegalCharacter << "]!" << std::endl;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
bool numberTooLow(const int number, const int min) {
|
||||||
bool numberTooLow(const int number, const int min)
|
if (number < min) {
|
||||||
{
|
|
||||||
if(number < min)
|
|
||||||
{
|
|
||||||
printNumberTooLow(number, min);
|
printNumberTooLow(number, min);
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool numberTooHigh(const int number, const int max)
|
bool numberTooHigh(const int number, const int max) {
|
||||||
{
|
if (number > max) {
|
||||||
if(number > max)
|
|
||||||
{
|
|
||||||
printNumberTooHigh(number, max);
|
printNumberTooHigh(number, max);
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool containsIllegalCharacter(const std::string s, const char illegalCharacter)
|
bool containsIllegalCharacter(const std::string s,
|
||||||
{
|
const char illegalCharacter) {
|
||||||
if( s.find(illegalCharacter) != std::string::npos)
|
if (s.find(illegalCharacter) != std::string::npos) {
|
||||||
{
|
|
||||||
printContainsIllegalCharacter(s, illegalCharacter);
|
printContainsIllegalCharacter(s, illegalCharacter);
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void e() { print("Poor man breakboint"); }
|
||||||
|
|
||||||
void e()
|
bool charIsNumber(const char c) { return c >= '0' && c <= '9'; }
|
||||||
{
|
|
||||||
print("Poor man breakboint");
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
bool charIsNumber(const char c)
|
|
||||||
{
|
|
||||||
return c >= '0' && c <= '9';
|
|
||||||
}
|
|
||||||
|
|
||||||
#endif
|
#endif
|
||||||
|
|||||||
@ -1,16 +1,14 @@
|
|||||||
#ifndef MAIN_CPP
|
#ifndef MAIN_CPP
|
||||||
#define MAIN_CPP
|
#define MAIN_CPP
|
||||||
|
|
||||||
|
#include "basic.cpp"
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
#include "basic.cpp"
|
|
||||||
|
|
||||||
std::vector <int> fillVector(const int min, const int max)
|
std::vector<int> fillVector(const int min, const int max) {
|
||||||
{
|
std::vector<int> newVector;
|
||||||
std::vector <int> newVector;
|
for (int i = min; i <= max; i++) {
|
||||||
for(int i = min; i <= max; i++)
|
|
||||||
{
|
|
||||||
newVector.push_back(i);
|
newVector.push_back(i);
|
||||||
}
|
}
|
||||||
return newVector;
|
return newVector;
|
||||||
@ -18,33 +16,27 @@ std::vector <int> fillVector(const int min, const int max)
|
|||||||
|
|
||||||
const int MAX_SPOT = 20;
|
const int MAX_SPOT = 20;
|
||||||
const int MIN_SPOT = 1;
|
const int MIN_SPOT = 1;
|
||||||
const std::vector <int> NORMAL_POINTS = fillVector(MIN_SPOT, MAX_SPOT);
|
const std::vector<int> NORMAL_POINTS = fillVector(MIN_SPOT, MAX_SPOT);
|
||||||
|
|
||||||
std::vector <int> multiplyVector(const std::vector <int> v, int multiplyBy)
|
std::vector<int> multiplyVector(const std::vector<int> v, int multiplyBy) {
|
||||||
{
|
std::vector<int> newVector;
|
||||||
std::vector <int> newVector;
|
for (unsigned int i = 0; i < v.size(); i++) {
|
||||||
for(unsigned int i = 0; i < v.size(); i++)
|
newVector.push_back(v.at(i) * multiplyBy);
|
||||||
{
|
|
||||||
newVector.push_back(v.at(i)*multiplyBy);
|
|
||||||
}
|
}
|
||||||
return newVector;
|
return newVector;
|
||||||
}
|
}
|
||||||
|
|
||||||
const std::vector <int> DOUBLE_POINTS = multiplyVector(NORMAL_POINTS, 2);
|
const std::vector<int> DOUBLE_POINTS = multiplyVector(NORMAL_POINTS, 2);
|
||||||
const std::vector <int> TRIPLE_POINTS = multiplyVector(NORMAL_POINTS, 3);
|
const std::vector<int> TRIPLE_POINTS = multiplyVector(NORMAL_POINTS, 3);
|
||||||
const int MAX_ONE_HIT = TRIPLE_POINTS.at(TRIPLE_POINTS.size() - 1);
|
const int MAX_ONE_HIT = TRIPLE_POINTS.at(TRIPLE_POINTS.size() - 1);
|
||||||
const int THROWS_IN_ONE_HIT = 3;
|
const int THROWS_IN_ONE_HIT = 3;
|
||||||
const int MAX_POINTS_TURN = THROWS_IN_ONE_HIT * MAX_ONE_HIT;
|
const int MAX_POINTS_TURN = THROWS_IN_ONE_HIT * MAX_ONE_HIT;
|
||||||
const int STARTING_POINTS = 501;
|
const int STARTING_POINTS = 501;
|
||||||
const int FINAL_POINTS = 0;
|
const int FINAL_POINTS = 0;
|
||||||
|
|
||||||
|
bool validString(const std::string s) {
|
||||||
bool validString(const std::string s)
|
for (unsigned int i = 0; i < s.length(); i++) {
|
||||||
{
|
if (!charIsNumber(s.at(i))) {
|
||||||
for(unsigned int i = 0; i < s.length(); i++)
|
|
||||||
{
|
|
||||||
if(!charIsNumber(s.at(i)))
|
|
||||||
{
|
|
||||||
printErrorStringContainsNotNumber(s);
|
printErrorStringContainsNotNumber(s);
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
@ -52,35 +44,33 @@ bool validString(const std::string s)
|
|||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool validNumberInput(const std::string input, const int min, const int max)
|
bool validNumberInput(const std::string input, const int min, const int max) {
|
||||||
{
|
if (!validString(input))
|
||||||
if(!validString(input)) return 0;
|
return 0;
|
||||||
int inputInt = std::stoi(input);
|
int inputInt = std::stoi(input);
|
||||||
if(numberTooLow(inputInt, min)) return 0;
|
if (numberTooLow(inputInt, min))
|
||||||
if(numberTooHigh(inputInt, max)) return 0;
|
return 0;
|
||||||
|
if (numberTooHigh(inputInt, max))
|
||||||
|
return 0;
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool validInput(const std::string s)
|
bool validInput(const std::string s) {
|
||||||
{
|
if (s.length() > 3)
|
||||||
if(s.length() > 3) return 0;
|
return 0;
|
||||||
if(!validNumberInput(s, FINAL_POINTS, STARTING_POINTS)) return 0;
|
if (!validNumberInput(s, FINAL_POINTS, STARTING_POINTS))
|
||||||
|
return 0;
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::vector <int> requiredShoots(const int pointsLeft)
|
std::vector<int> requiredShoots(const int pointsLeft) {}
|
||||||
{
|
|
||||||
|
|
||||||
}
|
int main() {
|
||||||
|
|
||||||
|
|
||||||
int main()
|
|
||||||
{
|
|
||||||
print("Enter points left: ");
|
print("Enter points left: ");
|
||||||
std::string pointsLeft;
|
std::string pointsLeft;
|
||||||
do{
|
do {
|
||||||
getline(std::cin, pointsLeft);
|
getline(std::cin, pointsLeft);
|
||||||
}while(!validInput(pointsLeft));
|
} while (!validInput(pointsLeft));
|
||||||
int pointsLeftInt = std::stoi(pointsLeft);
|
int pointsLeftInt = std::stoi(pointsLeft);
|
||||||
requiredShoots(pointsLeftInt);
|
requiredShoots(pointsLeftInt);
|
||||||
return 0;
|
return 0;
|
||||||
|
|||||||
@ -1,60 +1,50 @@
|
|||||||
#include <iostream>
|
|
||||||
#include <cmath>
|
#include <cmath>
|
||||||
|
#include <iostream>
|
||||||
|
|
||||||
const int PERCENTAGE = 44;
|
const int PERCENTAGE = 44;
|
||||||
const float PERCENTAGE_DENOMINATOR = 100;
|
const float PERCENTAGE_DENOMINATOR = 100;
|
||||||
const int NUMBERS_TO_CHECK = 200;
|
const int NUMBERS_TO_CHECK = 200;
|
||||||
const bool DEBUG = 0;
|
const bool DEBUG = 0;
|
||||||
|
|
||||||
bool isInteger(const float number)
|
bool isInteger(const float number) { return number == std::floor(number); }
|
||||||
{
|
|
||||||
return number == std::floor(number);
|
|
||||||
}
|
|
||||||
|
|
||||||
void printIsInteger(const int i, const int inputPercentage,
|
void printIsInteger(const int i, const int inputPercentage,
|
||||||
const float calculatedPercentage)
|
const float calculatedPercentage) {
|
||||||
{
|
std::cout << i << "*" << inputPercentage
|
||||||
std::cout << i << "*" << inputPercentage << "% is an integer number: "
|
<< "% is an integer number: " << i * calculatedPercentage
|
||||||
<< i*calculatedPercentage << std::endl;
|
<< std::endl;
|
||||||
}
|
}
|
||||||
|
|
||||||
void printDebug(const int i, const float calculatedPercentage)
|
void printDebug(const int i, const float calculatedPercentage) {
|
||||||
{
|
|
||||||
std::cout << "i = " << i << std::endl;
|
std::cout << "i = " << i << std::endl;
|
||||||
std::cout << i*calculatedPercentage << std::endl;
|
std::cout << i * calculatedPercentage << std::endl;
|
||||||
}
|
}
|
||||||
|
|
||||||
void isIntegerLoop( const bool debugOn = DEBUG,
|
void isIntegerLoop(const bool debugOn = DEBUG,
|
||||||
const int maxNumber = NUMBERS_TO_CHECK,
|
const int maxNumber = NUMBERS_TO_CHECK,
|
||||||
const int inputPercentage = PERCENTAGE )
|
const int inputPercentage = PERCENTAGE) {
|
||||||
{
|
|
||||||
float actualPercentage = inputPercentage / PERCENTAGE_DENOMINATOR;
|
float actualPercentage = inputPercentage / PERCENTAGE_DENOMINATOR;
|
||||||
for(int i = 1; i <= maxNumber; i++)
|
for (int i = 1; i <= maxNumber; i++) {
|
||||||
{
|
if (isInteger(i * actualPercentage)) {
|
||||||
if(isInteger(i*actualPercentage))
|
|
||||||
{
|
|
||||||
printIsInteger(i, inputPercentage, actualPercentage);
|
printIsInteger(i, inputPercentage, actualPercentage);
|
||||||
}
|
} else if (debugOn)
|
||||||
else if(debugOn) printDebug(i, actualPercentage);
|
printDebug(i, actualPercentage);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void printStartingMessage(const int maxNumber = NUMBERS_TO_CHECK,
|
void printStartingMessage(const int maxNumber = NUMBERS_TO_CHECK,
|
||||||
const int inputPercentage = PERCENTAGE)
|
const int inputPercentage = PERCENTAGE) {
|
||||||
{
|
|
||||||
std::cout << "For max number = " << maxNumber
|
std::cout << "For max number = " << maxNumber
|
||||||
<< "; and a percentage: " << inputPercentage
|
<< "; and a percentage: " << inputPercentage
|
||||||
<< "; Found following integer numbers: " << std::endl;
|
<< "; Found following integer numbers: " << std::endl;
|
||||||
}
|
}
|
||||||
|
|
||||||
void mainFunctions()
|
void mainFunctions() {
|
||||||
{
|
|
||||||
printStartingMessage();
|
printStartingMessage();
|
||||||
isIntegerLoop();
|
isIntegerLoop();
|
||||||
}
|
}
|
||||||
|
|
||||||
int main()
|
int main() {
|
||||||
{
|
|
||||||
mainFunctions();
|
mainFunctions();
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,48 +1,34 @@
|
|||||||
#include <iostream>
|
|
||||||
#include <vector>
|
|
||||||
#include <string>
|
|
||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
#include <fstream>
|
#include <fstream>
|
||||||
|
#include <iostream>
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
#ifndef CHECK_ISBN_CPP
|
#ifndef CHECK_ISBN_CPP
|
||||||
#define CHECK_ISBN_CPP
|
#define CHECK_ISBN_CPP
|
||||||
|
|
||||||
|
|
||||||
const bool DEBUG = 0;
|
const bool DEBUG = 0;
|
||||||
const int ISBN_LENGTH = 10;
|
const int ISBN_LENGTH = 10;
|
||||||
const int CHECK_NUMBER = 11;
|
const int CHECK_NUMBER = 11;
|
||||||
const unsigned long long int HIGHEST_ISBN = 9999999999;
|
const unsigned long long int HIGHEST_ISBN = 9999999999;
|
||||||
|
|
||||||
|
void printVector(std::vector<int> v) {
|
||||||
void printVector(std::vector <int> v)
|
for (unsigned int i = 0; i < v.size(); i++) {
|
||||||
{
|
|
||||||
for(unsigned int i = 0; i < v.size(); i++)
|
|
||||||
{
|
|
||||||
std::cout << v[i] << "; ";
|
std::cout << v[i] << "; ";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void print(const std::string printMe)
|
void print(const std::string printMe) { std::cout << printMe << std::endl; }
|
||||||
{
|
|
||||||
std::cout << printMe << std::endl;
|
|
||||||
}
|
|
||||||
|
|
||||||
void e()
|
void e() { print("PRINT"); }
|
||||||
{
|
|
||||||
print("PRINT");
|
|
||||||
}
|
|
||||||
|
|
||||||
bool checkInput(const std::string input)
|
bool checkInput(const std::string input) {
|
||||||
{
|
if (input.length() != ISBN_LENGTH) {
|
||||||
if(input.length() != ISBN_LENGTH)
|
|
||||||
{
|
|
||||||
print("Your number is too short/too long");
|
print("Your number is too short/too long");
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
for(int i = 0; i <= ISBN_LENGTH - 1; i++)
|
for (int i = 0; i <= ISBN_LENGTH - 1; i++) {
|
||||||
{
|
if (input.at(i) < '0' || input.at(i) > '9') {
|
||||||
if(input.at(i) < '0' || input.at(i) > '9')
|
|
||||||
{
|
|
||||||
print("Your number consists of illegal characters");
|
print("Your number consists of illegal characters");
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
@ -50,34 +36,26 @@ bool checkInput(const std::string input)
|
|||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::vector <int> stringToIntVector(const std::string input)
|
std::vector<int> stringToIntVector(const std::string input) {
|
||||||
{
|
std::vector<int> vector;
|
||||||
std::vector <int> vector;
|
for (int i = input.length() - 1; i >= 0; i--) {
|
||||||
for(int i = input.length() - 1; i >= 0; i--)
|
|
||||||
{
|
|
||||||
vector.push_back(input.at(i) - '0');
|
vector.push_back(input.at(i) - '0');
|
||||||
}
|
}
|
||||||
return vector;
|
return vector;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::vector <int> userISBN()
|
std::vector<int> userISBN() {
|
||||||
{
|
|
||||||
std::string input;
|
std::string input;
|
||||||
do{
|
do {
|
||||||
std::cout << "Enter the ISBN number (10 digits): ";
|
std::cout << "Enter the ISBN number (10 digits): ";
|
||||||
getline(std::cin, input);
|
getline(std::cin, input);
|
||||||
}while(!checkInput(input));
|
} while (!checkInput(input));
|
||||||
return stringToIntVector(input);
|
return stringToIntVector(input);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
bool checkISBN(const std::vector<int> isbn) {
|
||||||
|
|
||||||
|
|
||||||
bool checkISBN(const std::vector <int> isbn)
|
|
||||||
{
|
|
||||||
int sum = 0, t = 0;
|
int sum = 0, t = 0;
|
||||||
for(int i = 0; i < ISBN_LENGTH; i++)
|
for (int i = 0; i < ISBN_LENGTH; i++) {
|
||||||
{
|
|
||||||
t += isbn[i];
|
t += isbn[i];
|
||||||
sum += t;
|
sum += t;
|
||||||
}
|
}
|
||||||
@ -90,11 +68,9 @@ bool checkISBN(const std::vector <int> isbn)
|
|||||||
return !(sum % CHECK_NUMBER);
|
return !(sum % CHECK_NUMBER);
|
||||||
}
|
}
|
||||||
|
|
||||||
std::vector <int> intToVector(unsigned long long int number)
|
std::vector<int> intToVector(unsigned long long int number) {
|
||||||
{
|
std::vector<int> numbers;
|
||||||
std::vector <int> numbers;
|
while (number > 0) {
|
||||||
while(number > 0)
|
|
||||||
{
|
|
||||||
numbers.push_back(number % 10);
|
numbers.push_back(number % 10);
|
||||||
number /= 10;
|
number /= 10;
|
||||||
}
|
}
|
||||||
@ -103,18 +79,13 @@ std::vector <int> intToVector(unsigned long long int number)
|
|||||||
return numbers;
|
return numbers;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
int checkAll() {
|
||||||
|
|
||||||
int checkAll()
|
|
||||||
{
|
|
||||||
int sum = 0;
|
int sum = 0;
|
||||||
std::ofstream file;
|
std::ofstream file;
|
||||||
file.open("ISBN.txt");
|
file.open("ISBN.txt");
|
||||||
for(unsigned long long int i = HIGHEST_ISBN; i >= 1; i--)
|
for (unsigned long long int i = HIGHEST_ISBN; i >= 1; i--) {
|
||||||
{
|
// if(DEBUG) std::cout << i << std::endl;
|
||||||
//if(DEBUG) std::cout << i << std::endl;
|
if (checkISBN(intToVector(i))) {
|
||||||
if( checkISBN(intToVector(i)) )
|
|
||||||
{
|
|
||||||
++sum;
|
++sum;
|
||||||
file << std::to_string(i) << "\n";
|
file << std::to_string(i) << "\n";
|
||||||
}
|
}
|
||||||
@ -124,8 +95,7 @@ int checkAll()
|
|||||||
return sum;
|
return sum;
|
||||||
}
|
}
|
||||||
|
|
||||||
int main()
|
int main() {
|
||||||
{
|
|
||||||
checkAll();
|
checkAll();
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,44 +1,35 @@
|
|||||||
#include <iostream>
|
#include <iostream>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
|
struct charOccurence {
|
||||||
struct charOccurence
|
|
||||||
{
|
|
||||||
char c;
|
char c;
|
||||||
int occurrence;
|
int occurrence;
|
||||||
};
|
};
|
||||||
|
|
||||||
void printCharOccurenceVector(const std::vector <charOccurence> v)
|
void printCharOccurenceVector(const std::vector<charOccurence> v) {
|
||||||
{
|
|
||||||
std::cout << "[";
|
std::cout << "[";
|
||||||
for(unsigned int i = 0; i < v.size(); i++)
|
for (unsigned int i = 0; i < v.size(); i++) {
|
||||||
{
|
std::cout << "(\"" << v.at(i).c << "\", " << v.at(i).occurrence << ")"
|
||||||
std::cout << "(\"" << v.at(i).c << "\", " << v.at(i).occurrence << ")" << (i + 1 == v.size() ? "" : ", ");
|
<< (i + 1 == v.size() ? "" : ", ");
|
||||||
}
|
}
|
||||||
std::cout << "]" << std::endl;
|
std::cout << "]" << std::endl;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
int main() {
|
||||||
int main()
|
std::vector<charOccurence> list;
|
||||||
{
|
|
||||||
std::vector <charOccurence> list;
|
|
||||||
std::string userInput = "aaaabbbcca";
|
std::string userInput = "aaaabbbcca";
|
||||||
charOccurence newCharOccurence;
|
charOccurence newCharOccurence;
|
||||||
newCharOccurence.c = userInput.at(0);
|
newCharOccurence.c = userInput.at(0);
|
||||||
newCharOccurence.occurrence = 1;
|
newCharOccurence.occurrence = 1;
|
||||||
for(unsigned int i = 1, j = 1; i < userInput.length(); i++)
|
for (unsigned int i = 1, j = 1; i < userInput.length(); i++) {
|
||||||
{
|
|
||||||
char newCharacter = userInput.at(i);
|
char newCharacter = userInput.at(i);
|
||||||
if(newCharacter != newCharOccurence.c)
|
if (newCharacter != newCharOccurence.c) {
|
||||||
{
|
|
||||||
list.push_back(newCharOccurence);
|
list.push_back(newCharOccurence);
|
||||||
j = 1;
|
j = 1;
|
||||||
newCharOccurence.c = newCharacter;
|
newCharOccurence.c = newCharacter;
|
||||||
newCharOccurence.occurrence = j;
|
newCharOccurence.occurrence = j;
|
||||||
|
|
||||||
}else
|
} else {
|
||||||
{
|
|
||||||
newCharOccurence.occurrence++;
|
newCharOccurence.occurrence++;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,10 +1,10 @@
|
|||||||
#ifndef BASIC_CPP
|
#ifndef BASIC_CPP
|
||||||
#define BASIC_CPP
|
#define BASIC_CPP
|
||||||
|
|
||||||
|
#include <fstream>
|
||||||
|
#include <iostream>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
#include <iostream>
|
|
||||||
#include <fstream>
|
|
||||||
|
|
||||||
void print(const std::string s) { std::cout << s << std::endl; }
|
void print(const std::string s) { std::cout << s << std::endl; }
|
||||||
|
|
||||||
@ -14,102 +14,86 @@ void e() { print("Poor man breakboint"); }
|
|||||||
|
|
||||||
bool charIsNumber(const char c) { return c >= '0' && c <= '9'; }
|
bool charIsNumber(const char c) { return c >= '0' && c <= '9'; }
|
||||||
|
|
||||||
void printStringNewLine(const std::string s)
|
void printStringNewLine(const std::string s) {
|
||||||
{
|
|
||||||
std::cout << "string: " << std::endl;
|
std::cout << "string: " << std::endl;
|
||||||
std::cout << "\"" << s << "\"" << std::endl;
|
std::cout << "\"" << s << "\"" << std::endl;
|
||||||
}
|
}
|
||||||
|
|
||||||
void printStringContainsNotNumbers(const std::string s, const int position)
|
void printStringContainsNotNumbers(const std::string s, const int position) {
|
||||||
{
|
|
||||||
printStringNewLine(s);
|
printStringNewLine(s);
|
||||||
std::cout << "contains character different than number at position: " << position
|
std::cout << "contains character different than number at position: "
|
||||||
<< "; this character is: " << s.at(position) << std::endl;
|
<< position << "; this character is: " << s.at(position)
|
||||||
|
<< std::endl;
|
||||||
}
|
}
|
||||||
|
|
||||||
void printStringContainsNumbers(const std::string s, const int position)
|
void printStringContainsNumbers(const std::string s, const int position) {
|
||||||
{
|
|
||||||
printStringNewLine(s);
|
printStringNewLine(s);
|
||||||
std::cout << "contains number at postion: " << position
|
std::cout << "contains number at postion: " << position
|
||||||
<< "; this number is: " << s.at(position) << std::endl;
|
<< "; this number is: " << s.at(position) << std::endl;
|
||||||
}
|
}
|
||||||
|
|
||||||
void printNumberTooLow(const int number, const int min)
|
void printNumberTooLow(const int number, const int min) {
|
||||||
{
|
std::cout << "number: " << number << " is too low. Minimal number is: " << min
|
||||||
std::cout << "number: " << number
|
<< std::endl;
|
||||||
<< " is too low. Minimal number is: " << min << std::endl;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void printNumberTooHigh(const int number, const int max)
|
void printNumberTooHigh(const int number, const int max) {
|
||||||
{
|
|
||||||
std::cout << "number: " << number
|
std::cout << "number: " << number
|
||||||
<< " is too high. Maximal number is: " << max << std::endl;
|
<< " is too high. Maximal number is: " << max << std::endl;
|
||||||
}
|
}
|
||||||
|
|
||||||
void printNotValidStringLength(const std::string s, const int desiredLength)
|
void printNotValidStringLength(const std::string s, const int desiredLength) {
|
||||||
{
|
|
||||||
printStringNewLine(s);
|
printStringNewLine(s);
|
||||||
std::cout << "is too short/too long, it is: "
|
std::cout << "is too short/too long, it is: " << s.length()
|
||||||
<< s.length() << " characters long but should be: " << desiredLength
|
<< " characters long but should be: " << desiredLength
|
||||||
<< " characters long " << std::endl;
|
<< " characters long " << std::endl;
|
||||||
}
|
}
|
||||||
|
|
||||||
void printInvalidCharacter(const char c, const char desiredCharacter)
|
void printInvalidCharacter(const char c, const char desiredCharacter) {
|
||||||
{
|
|
||||||
std::cout << "[ " << c << " ] Is invalid character, expected: [ "
|
std::cout << "[ " << c << " ] Is invalid character, expected: [ "
|
||||||
<< desiredCharacter << " ]" << std::endl;
|
<< desiredCharacter << " ]" << std::endl;
|
||||||
}
|
}
|
||||||
|
|
||||||
void printContainsIllegalCharacter( const std::string s,
|
void printContainsIllegalCharacter(const std::string s,
|
||||||
const char illegalCharacter )
|
const char illegalCharacter) {
|
||||||
{
|
|
||||||
printStringNewLine(s);
|
printStringNewLine(s);
|
||||||
std::cout << " consists of illegal sign: ["
|
std::cout << " consists of illegal sign: [" << illegalCharacter << "]!"
|
||||||
<< illegalCharacter << "]!" << std::endl;
|
<< std::endl;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
bool numberTooLow(const int number, const int min) {
|
||||||
bool numberTooLow(const int number, const int min)
|
if (number < min) {
|
||||||
{
|
|
||||||
if(number < min)
|
|
||||||
{
|
|
||||||
printNumberTooLow(number, min);
|
printNumberTooLow(number, min);
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool numberTooHigh(const int number, const int max)
|
bool numberTooHigh(const int number, const int max) {
|
||||||
{
|
if (number > max) {
|
||||||
if(number > max)
|
|
||||||
{
|
|
||||||
printNumberTooHigh(number, max);
|
printNumberTooHigh(number, max);
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool containsIllegalCharacter(const std::string s, const char illegalCharacter)
|
bool containsIllegalCharacter(const std::string s,
|
||||||
{
|
const char illegalCharacter) {
|
||||||
if( s.find(illegalCharacter) != std::string::npos)
|
if (s.find(illegalCharacter) != std::string::npos) {
|
||||||
{
|
|
||||||
printContainsIllegalCharacter(s, illegalCharacter);
|
printContainsIllegalCharacter(s, illegalCharacter);
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
void printStringVector(const std::vector <std::string> vector)
|
void printStringVector(const std::vector<std::string> vector) {
|
||||||
{
|
for (unsigned int i = 0; i < vector.size(); i++)
|
||||||
for(unsigned int i = 0; i < vector.size(); i++) print(vector.at(i));
|
print(vector.at(i));
|
||||||
}
|
}
|
||||||
|
|
||||||
bool stringContainsNotNumbers(const std::string s)
|
bool stringContainsNotNumbers(const std::string s) {
|
||||||
{
|
for (unsigned int i = 0; i < s.length(); i++) {
|
||||||
for(unsigned int i = 0; i < s.length(); i++)
|
if (!charIsNumber(s.at(i))) {
|
||||||
{
|
|
||||||
if(!charIsNumber(s.at(i)))
|
|
||||||
{
|
|
||||||
printStringContainsNotNumbers(s, i);
|
printStringContainsNotNumbers(s, i);
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
@ -117,12 +101,9 @@ bool stringContainsNotNumbers(const std::string s)
|
|||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool stringContainsNumbers(const std::string s)
|
bool stringContainsNumbers(const std::string s) {
|
||||||
{
|
for (unsigned int i = 0; i < s.length(); i++) {
|
||||||
for(unsigned int i = 0; i < s.length(); i++)
|
if (charIsNumber(s.at(i))) {
|
||||||
{
|
|
||||||
if(charIsNumber(s.at(i)))
|
|
||||||
{
|
|
||||||
printStringContainsNumbers(s, i);
|
printStringContainsNumbers(s, i);
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
@ -130,43 +111,34 @@ bool stringContainsNumbers(const std::string s)
|
|||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool validStringLength(const std::string s, const int desiredLength)
|
bool validStringLength(const std::string s, const int desiredLength) {
|
||||||
{
|
|
||||||
int stringLength = s.length();
|
int stringLength = s.length();
|
||||||
if(stringLength != desiredLength)
|
if (stringLength != desiredLength) {
|
||||||
{
|
|
||||||
printNotValidStringLength(s, desiredLength);
|
printNotValidStringLength(s, desiredLength);
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool validCharacter(const char inputC, const char desiredC)
|
bool validCharacter(const char inputC, const char desiredC) {
|
||||||
{
|
if (inputC != desiredC) {
|
||||||
if(inputC != desiredC)
|
|
||||||
{
|
|
||||||
printInvalidCharacter(inputC, desiredC);
|
printInvalidCharacter(inputC, desiredC);
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
void vectorToFile(const std::vector <std::string> strings, std::ofstream &file)
|
void vectorToFile(const std::vector<std::string> strings, std::ofstream &file) {
|
||||||
{
|
for (unsigned int i = 0; i < strings.size(); i++) {
|
||||||
for(unsigned int i = 0; i < strings.size(); i++)
|
|
||||||
{
|
|
||||||
file << strings.at(i) << std::endl;
|
file << strings.at(i) << std::endl;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
std::vector <std::string> fileToVector(std::ifstream &file,
|
std::vector<std::string> fileToVector(std::ifstream &file,
|
||||||
std::vector <std::string> strings)
|
std::vector<std::string> strings) {
|
||||||
{
|
|
||||||
std::string line;
|
std::string line;
|
||||||
if(file.is_open())
|
if (file.is_open()) {
|
||||||
{
|
while (getline(file, line)) {
|
||||||
while(getline(file, line))
|
|
||||||
{
|
|
||||||
strings.push_back(line);
|
strings.push_back(line);
|
||||||
}
|
}
|
||||||
file.close();
|
file.close();
|
||||||
|
|||||||
@ -1,25 +1,22 @@
|
|||||||
#ifndef MAIN_CPP
|
#ifndef MAIN_CPP
|
||||||
#define MAIN_CPP
|
#define MAIN_CPP
|
||||||
|
|
||||||
#include <string>
|
|
||||||
#include <iostream>
|
|
||||||
#include <vector>
|
|
||||||
#include "basic.cpp"
|
#include "basic.cpp"
|
||||||
|
#include <iostream>
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
struct wordOccurences
|
struct wordOccurences {
|
||||||
{
|
|
||||||
std::string word;
|
std::string word;
|
||||||
int occurences;
|
int occurences;
|
||||||
}
|
}
|
||||||
|
|
||||||
struct previousWords
|
struct previousWords {
|
||||||
{
|
|
||||||
std::string word;
|
std::string word;
|
||||||
std::vector <wordOccurences> previousWords;
|
std::vector<wordOccurences> previousWords;
|
||||||
};
|
};
|
||||||
|
|
||||||
struct wordProbabiliy
|
struct wordProbabiliy {
|
||||||
{
|
|
||||||
std::string previousWord;
|
std::string previousWord;
|
||||||
std::string nextWord;
|
std::string nextWord;
|
||||||
float probability;
|
float probability;
|
||||||
@ -27,25 +24,23 @@ struct wordProbabiliy
|
|||||||
|
|
||||||
bool validInput(const std::string userInput)
|
bool validInput(const std::string userInput)
|
||||||
{
|
{
|
||||||
if(stringContainsNumbers(userInput)) return 0;
|
if (stringContainsNumbers(userInput))
|
||||||
|
return 0;
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::vector <std::string> divideIntoWords(const std::string userInput)
|
std::vector<std::string> divideIntoWords(const std::string userInput) {
|
||||||
{
|
std::vector<std::string> words;
|
||||||
std::vector <std::string> words;
|
|
||||||
int inputLength = userInput.length();
|
int inputLength = userInput.length();
|
||||||
int wordLength = 0;
|
int wordLength = 0;
|
||||||
for(int i = 0; i < inputLength; i++)
|
for (int i = 0; i < inputLength; i++) {
|
||||||
{
|
if (userInput.at(i) == ' ') {
|
||||||
if(userInput.at(i) == ' ')
|
|
||||||
{
|
|
||||||
words.push_back(userInput.substr(i - wordLength, wordLength));
|
words.push_back(userInput.substr(i - wordLength, wordLength));
|
||||||
wordLength = 0;
|
wordLength = 0;
|
||||||
}else wordLength++;
|
} else
|
||||||
|
wordLength++;
|
||||||
|
|
||||||
if(i + 1 == inputLength)
|
if (i + 1 == inputLength) {
|
||||||
{
|
|
||||||
words.push_back(userInput.substr(i - wordLength + 1, wordLength + 1));
|
words.push_back(userInput.substr(i - wordLength + 1, wordLength + 1));
|
||||||
wordLength = 0;
|
wordLength = 0;
|
||||||
}
|
}
|
||||||
@ -53,30 +48,28 @@ std::vector <std::string> divideIntoWords(const std::string userInput)
|
|||||||
return words;
|
return words;
|
||||||
}
|
}
|
||||||
|
|
||||||
int wordRepeats(const std::vector <previousWords> wordsList, const std::string word)
|
int wordRepeats(const std::vector<previousWords> wordsList,
|
||||||
{
|
const std::string word) {
|
||||||
int wordsSize = wordsList.size();
|
int wordsSize = wordsList.size();
|
||||||
for(int i = 0; i < wordsSize; i++)
|
for (int i = 0; i < wordsSize; i++) {
|
||||||
{
|
if (wordsList.at(i).word == word)
|
||||||
if(wordsList.at(i).word == word) return i;
|
return i;
|
||||||
}
|
}
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool alreadyExists(const std::vector <previousWords> wordsList, const std::string s)
|
bool alreadyExists(const std::vector<previousWords> wordsList,
|
||||||
{
|
const std::string s) {
|
||||||
for(unsigned int i = 0; i < wordsList.size(); i++)
|
for (unsigned int i = 0; i < wordsList.size(); i++) {
|
||||||
{
|
|
||||||
if(s == wordsList.previousWOrds
|
if(s == wordsList.previousWOrds
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
std::vector <previousWords> getWordsAndTheirPrevious(const std::vector <std::string> words)
|
std::vector<previousWords>
|
||||||
{
|
getWordsAndTheirPrevious(const std::vector<std::string> words) {
|
||||||
std::vector <previousWords> wordsList;
|
std::vector<previousWords> wordsList;
|
||||||
int wordsSize = words.size();
|
int wordsSize = words.size();
|
||||||
for(int i = 1; i < wordsSize; i++)
|
for (int i = 1; i < wordsSize; i++) {
|
||||||
{
|
|
||||||
previousWords temp;
|
previousWords temp;
|
||||||
temp.word = words.at(i);
|
temp.word = words.at(i);
|
||||||
wordOccurences tempTwo;
|
wordOccurences tempTwo;
|
||||||
@ -84,53 +77,46 @@ std::vector <previousWords> getWordsAndTheirPrevious(const std::vector <std::str
|
|||||||
tempTwo.occurences = 1;
|
tempTwo.occurences = 1;
|
||||||
temp.previousWords.push_back(tempTwo);
|
temp.previousWords.push_back(tempTwo);
|
||||||
int position = wordRepeats(wordsList, temp.word);
|
int position = wordRepeats(wordsList, temp.word);
|
||||||
if(position == -1)
|
if (position == -1) {
|
||||||
{
|
|
||||||
wordsList.push_back(temp);
|
wordsList.push_back(temp);
|
||||||
}else
|
} else {
|
||||||
{
|
|
||||||
|
|
||||||
wordsList.at(position).previousWords.push_back(temp.previousWords.at(0));
|
wordsList.at(position).previousWords.push_back(
|
||||||
|
temp.previousWords.at(0));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return wordsList;
|
return wordsList;
|
||||||
}
|
}
|
||||||
|
|
||||||
void printPreviousWord(const previousWords word)
|
void printPreviousWord(const previousWords word) {
|
||||||
{
|
std::cout << "The word is \"" << word.word
|
||||||
std::cout << "The word is \"" << word.word << "\" Words before it are: " << std::endl;
|
<< "\" Words before it are: " << std::endl;
|
||||||
for(unsigned int i = 0; i < word.previousWords.size(); i++)
|
for (unsigned int i = 0; i < word.previousWords.size(); i++) {
|
||||||
{
|
|
||||||
print(word.previousWords.at(i));
|
print(word.previousWords.at(i));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void printPreviousWordsVector(const std::vector<previousWords> v) {
|
||||||
void printPreviousWordsVector(const std::vector <previousWords> v)
|
for (unsigned int i = 0; i < v.size(); i++) {
|
||||||
{
|
|
||||||
for(unsigned int i = 0; i < v.size(); i++)
|
|
||||||
{
|
|
||||||
printPreviousWord(v.at(i));
|
printPreviousWord(v.at(i));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
std::vector <wordProbability> getWordProbability(const std::vector <previousWords> wordsList)
|
std::vector<wordProbability>
|
||||||
{
|
getWordProbability(const std::vector<previousWords> wordsList) {
|
||||||
std::vector <wordProbability> probalityVector;
|
std::vector<wordProbability> probalityVector;
|
||||||
for(unsigned int i = 0; i - 1 < wordsList.size(); i++)
|
for (unsigned int i = 0; i - 1 < wordsList.size(); i++) {
|
||||||
{
|
|
||||||
pro
|
pro
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
int main()
|
int main() {
|
||||||
{
|
|
||||||
std::string userInput;
|
std::string userInput;
|
||||||
do{
|
do {
|
||||||
getline(std::cin, userInput);
|
getline(std::cin, userInput);
|
||||||
}while(!validInput(userInput));
|
} while (!validInput(userInput));
|
||||||
std::vector <std::string> words = divideIntoWords(userInput);
|
std::vector<std::string> words = divideIntoWords(userInput);
|
||||||
std::vector <previousWords> prev = getWordsAndTheirPrevious(words);
|
std::vector<previousWords> prev = getWordsAndTheirPrevious(words);
|
||||||
printPreviousWordsVector(prev);
|
printPreviousWordsVector(prev);
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,23 +1,19 @@
|
|||||||
#include <iostream>
|
#include <iostream>
|
||||||
|
|
||||||
|
int multiplication(int a, int b) {
|
||||||
int multiplication(int a, int b)
|
|
||||||
{
|
|
||||||
int answer = 0;
|
int answer = 0;
|
||||||
for(int i = 0; i < a; i++)
|
for (int i = 0; i < a; i++) {
|
||||||
{
|
|
||||||
answer += b;
|
answer += b;
|
||||||
}
|
}
|
||||||
if(answer != a*b)
|
if (answer != a * b) {
|
||||||
{
|
|
||||||
std::cout << "There is a mistake in your code!" << std::endl;
|
std::cout << "There is a mistake in your code!" << std::endl;
|
||||||
return -1;
|
return -1;
|
||||||
} else return answer;
|
} else
|
||||||
|
return answer;
|
||||||
}
|
}
|
||||||
|
|
||||||
int main()
|
int main() {
|
||||||
{
|
int a, b;
|
||||||
int a,b;
|
|
||||||
std::cout << "Enter number a" << std::endl;
|
std::cout << "Enter number a" << std::endl;
|
||||||
std::cin >> a;
|
std::cin >> a;
|
||||||
std::cout << "Enter number b" << std::endl;
|
std::cout << "Enter number b" << std::endl;
|
||||||
|
|||||||
@ -1,21 +1,19 @@
|
|||||||
#include <iostream>
|
#include <iostream>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
int sumStartEnd(int start, int end)
|
int sumStartEnd(int start, int end) {
|
||||||
{
|
|
||||||
int sum = 0;
|
int sum = 0;
|
||||||
for(int i = start; i <= end; i++)
|
for (int i = start; i <= end; i++) {
|
||||||
{
|
|
||||||
sum += i;
|
sum += i;
|
||||||
}
|
}
|
||||||
return sum;
|
return sum;
|
||||||
}
|
}
|
||||||
|
|
||||||
int main()
|
int main() {
|
||||||
{
|
|
||||||
std::cout << "Krzysztof" << std::endl;
|
std::cout << "Krzysztof" << std::endl;
|
||||||
for(int i = 700; i >= 200; i -= 13) std::cout << i << std::endl;
|
for (int i = 700; i >= 200; i -= 13)
|
||||||
std::vector <int> array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
|
std::cout << i << std::endl;
|
||||||
|
std::vector<int> array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
|
||||||
// if SECOND means 0, 1, TWO
|
// if SECOND means 0, 1, TWO
|
||||||
std::cout << array[2] << std::endl;
|
std::cout << array[2] << std::endl;
|
||||||
// if SECOND means 1, TWO
|
// if SECOND means 1, TWO
|
||||||
@ -25,32 +23,36 @@ int main()
|
|||||||
std::string userName;
|
std::string userName;
|
||||||
std::cout << std::endl;
|
std::cout << std::endl;
|
||||||
getline(std::cin, userName);
|
getline(std::cin, userName);
|
||||||
if(userName == "Jack") std::cout << "Hi Jack!" << std::endl;
|
if (userName == "Jack")
|
||||||
else std::cout << "Hello, " << userName << std::endl;
|
std::cout << "Hi Jack!" << std::endl;
|
||||||
|
else
|
||||||
|
std::cout << "Hello, " << userName << std::endl;
|
||||||
|
|
||||||
for(int i = 0; i <= 100; i++)
|
for (int i = 0; i <= 100; i++) {
|
||||||
{
|
if (i % 2 == 0)
|
||||||
if(i % 2 == 0) std::cout << i << " is an even number" << std::endl;
|
std::cout << i << " is an even number" << std::endl;
|
||||||
else std::cout << i << " is an odd number" << std::endl;
|
else
|
||||||
|
std::cout << i << " is an odd number" << std::endl;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool flag = 1;
|
bool flag = 1;
|
||||||
for(int i = 0; i <= 100; i++)
|
for (int i = 0; i <= 100; i++) {
|
||||||
{
|
if (flag)
|
||||||
if(flag) std::cout << i << " is an even number" << std::endl;
|
std::cout << i << " is an even number" << std::endl;
|
||||||
else std::cout << i << " is an odd number" << std::endl;
|
else
|
||||||
|
std::cout << i << " is an odd number" << std::endl;
|
||||||
flag = -flag;
|
flag = -flag;
|
||||||
}
|
}
|
||||||
|
|
||||||
for(int i = 0; i <= 100; i += 2) std::cout << i << " is an even number " << std::endl;
|
for (int i = 0; i <= 100; i += 2)
|
||||||
for(int i = 1; i <= 99; i += 2) std::cout << i << " is an odd number " << std::endl;
|
std::cout << i << " is an even number " << std::endl;
|
||||||
|
for (int i = 1; i <= 99; i += 2)
|
||||||
|
std::cout << i << " is an odd number " << std::endl;
|
||||||
|
|
||||||
for(int i = 1, j = 1; j <= 12; i++)
|
for (int i = 1, j = 1; j <= 12; i++) {
|
||||||
{
|
|
||||||
std::cout << i * j << " ";
|
std::cout << i * j << " ";
|
||||||
|
|
||||||
if(i == 12)
|
if (i == 12) {
|
||||||
{
|
|
||||||
i = 1;
|
i = 1;
|
||||||
j++;
|
j++;
|
||||||
std::cout << std::endl;
|
std::cout << std::endl;
|
||||||
@ -60,37 +62,38 @@ int main()
|
|||||||
std::cout << std::endl;
|
std::cout << std::endl;
|
||||||
std::string sentence;
|
std::string sentence;
|
||||||
getline(std::cin, sentence);
|
getline(std::cin, sentence);
|
||||||
std::vector <std::string> words;
|
std::vector<std::string> words;
|
||||||
std::string temp;
|
std::string temp;
|
||||||
for(unsigned int i = 0; i < sentence.length(); i++)
|
for (unsigned int i = 0; i < sentence.length(); i++) {
|
||||||
{
|
if (sentence.at(i) == ' ' || i + 1 == sentence.length()) {
|
||||||
if(sentence.at(i) == ' ' || i + 1 == sentence.length())
|
if (i + 1 == sentence.length())
|
||||||
{
|
temp.push_back(sentence.at(i));
|
||||||
if(i + 1 == sentence.length()) temp.push_back(sentence.at(i));
|
|
||||||
words.push_back(temp);
|
words.push_back(temp);
|
||||||
temp = "";
|
temp = "";
|
||||||
}else temp.push_back(sentence.at(i));
|
} else
|
||||||
|
temp.push_back(sentence.at(i));
|
||||||
}
|
}
|
||||||
|
|
||||||
for(unsigned int i = 0; i < words.size(); i++)
|
for (unsigned int i = 0; i < words.size(); i++) {
|
||||||
{
|
|
||||||
std::cout << words[i] << std::endl;
|
std::cout << words[i] << std::endl;
|
||||||
}
|
}
|
||||||
|
|
||||||
int score;
|
int score;
|
||||||
char project;
|
char project;
|
||||||
std::vector <char> GRADES = {'F', 'C', 'B', 'A'};
|
std::vector<char> GRADES = {'F', 'C', 'B', 'A'};
|
||||||
std::cin >> score;
|
std::cin >> score;
|
||||||
std::cout << std::endl;
|
std::cout << std::endl;
|
||||||
std::cin >> project;
|
std::cin >> project;
|
||||||
std::cout << std::endl;
|
std::cout << std::endl;
|
||||||
bool doneProject = 0;
|
bool doneProject = 0;
|
||||||
if(project == 'Y') doneProject = 1;
|
if (project == 'Y')
|
||||||
if(score < 50) std::cout << GRADES[0 + doneProject];
|
doneProject = 1;
|
||||||
else if(score < 70) std::cout << GRADES[1 + doneProject];
|
if (score < 50)
|
||||||
else if(score < 90) std::cout << GRADES[2 + doneProject];
|
std::cout << GRADES[0 + doneProject];
|
||||||
else std::cout << GRADES[3];
|
else if (score < 70)
|
||||||
|
std::cout << GRADES[1 + doneProject];
|
||||||
|
else if (score < 90)
|
||||||
|
std::cout << GRADES[2 + doneProject];
|
||||||
|
else
|
||||||
|
std::cout << GRADES[3];
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,10 +1,10 @@
|
|||||||
#include <random>
|
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
|
#include <random>
|
||||||
|
|
||||||
int main() {
|
int main() {
|
||||||
std::random_device rd;
|
std::random_device rd;
|
||||||
std::uniform_real_distribution<double> dist(1.0, 10.0);
|
std::uniform_real_distribution<double> dist(1.0, 10.0);
|
||||||
|
|
||||||
for (int i=0; i<16; ++i)
|
for (int i = 0; i < 16; ++i)
|
||||||
std::cout << dist(rd) << "\n";
|
std::cout << dist(rd) << "\n";
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,15 +1,13 @@
|
|||||||
|
#include <algorithm>
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <algorithm>
|
|
||||||
|
|
||||||
int main()
|
int main() {
|
||||||
{
|
|
||||||
std::string userString;
|
std::string userString;
|
||||||
getline(std::cin, userString);
|
getline(std::cin, userString);
|
||||||
int sLength = userString.length();
|
int sLength = userString.length();
|
||||||
std::string tempString = userString;
|
std::string tempString = userString;
|
||||||
for(int i = 0; i < sLength/2; i++)
|
for (int i = 0; i < sLength / 2; i++) {
|
||||||
{
|
|
||||||
char temp = tempString[sLength - 1 - i];
|
char temp = tempString[sLength - 1 - i];
|
||||||
tempString[sLength - 1 - i] = tempString[i];
|
tempString[sLength - 1 - i] = tempString[i];
|
||||||
tempString[i] = temp;
|
tempString[i] = temp;
|
||||||
|
|||||||
@ -1,6 +1,6 @@
|
|||||||
#include <iostream>
|
#include <iostream>
|
||||||
#include <string>
|
|
||||||
#include <math.h>
|
#include <math.h>
|
||||||
|
#include <string>
|
||||||
|
|
||||||
const std::string ENTER = "Enter quadratic equation constants: ";
|
const std::string ENTER = "Enter quadratic equation constants: ";
|
||||||
const std::string WHAT_TO_INPUT = "a, b, c as in: ax^2 + bx + c = 0";
|
const std::string WHAT_TO_INPUT = "a, b, c as in: ax^2 + bx + c = 0";
|
||||||
@ -8,31 +8,24 @@ const std::string START = ENTER + WHAT_TO_INPUT;
|
|||||||
|
|
||||||
void print(const std::string s) { std::cout << s << std::endl; }
|
void print(const std::string s) { std::cout << s << std::endl; }
|
||||||
|
|
||||||
float getDelta(float a, float b, float c)
|
float getDelta(float a, float b, float c) { return b * b - 4 * a * c; }
|
||||||
{
|
|
||||||
return b*b - 4*a*c;
|
float calculateFirstTerm(float a, float b, float delta) {
|
||||||
|
return (-b - sqrt(delta)) / (2 * a);
|
||||||
}
|
}
|
||||||
|
|
||||||
float calculateFirstTerm(float a, float b, float delta)
|
float calculateSecondTerm(float a, float b, float delta) {
|
||||||
{
|
return (-b + sqrt(delta)) / (2 * a);
|
||||||
return (-b - sqrt(delta))/(2*a);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
float calculateSecondTerm(float a, float b, float delta)
|
int main() {
|
||||||
{
|
|
||||||
return (-b + sqrt(delta))/(2*a);
|
|
||||||
}
|
|
||||||
|
|
||||||
int main()
|
|
||||||
{
|
|
||||||
print(START);
|
print(START);
|
||||||
float a, b, c;
|
float a, b, c;
|
||||||
std::cin >> a;
|
std::cin >> a;
|
||||||
std::cin >> b;
|
std::cin >> b;
|
||||||
std::cin >> c;
|
std::cin >> c;
|
||||||
float delta = getDelta(a, b, c);
|
float delta = getDelta(a, b, c);
|
||||||
if(delta < 0)
|
if (delta < 0) {
|
||||||
{
|
|
||||||
print("delta smaller than 0");
|
print("delta smaller than 0");
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
@ -43,6 +36,4 @@ int main()
|
|||||||
std::cout << "x_1 = " << x_1 << std::endl;
|
std::cout << "x_1 = " << x_1 << std::endl;
|
||||||
std::cout << "x_2 = " << x_2 << std::endl;
|
std::cout << "x_2 = " << x_2 << std::endl;
|
||||||
return 0;
|
return 0;
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,82 +1,90 @@
|
|||||||
#include <iostream>
|
#include <iostream>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
void printField(std::vector<unsigned int> &field)
|
void printField(std::vector<unsigned int> &field) {
|
||||||
{
|
|
||||||
std::cout << std::endl;
|
std::cout << std::endl;
|
||||||
for(int i = 0; i < 9; i++)
|
for (int i = 0; i < 9; i++) {
|
||||||
{
|
if (i % 3 == 0)
|
||||||
if(i % 3 == 0) std::cout << std::endl;
|
std::cout << std::endl;
|
||||||
if(field[i] == 0) std::cout << "-";
|
if (field[i] == 0)
|
||||||
else if(field[i] == 1) std::cout << "X";
|
std::cout << "-";
|
||||||
else if(field[i] == 2) std::cout << "O";
|
else if (field[i] == 1)
|
||||||
|
std::cout << "X";
|
||||||
|
else if (field[i] == 2)
|
||||||
|
std::cout << "O";
|
||||||
}
|
}
|
||||||
std::cout << std::endl;
|
std::cout << std::endl;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
unsigned int chooseField(unsigned int playerNumber,
|
||||||
unsigned int chooseField(unsigned int playerNumber, std::vector<unsigned int> &field)
|
std::vector<unsigned int> &field) {
|
||||||
{
|
|
||||||
unsigned int chosenField;
|
unsigned int chosenField;
|
||||||
do
|
do {
|
||||||
{
|
|
||||||
std::cout << "player " << playerNumber << " choose a field:" << std::endl;
|
std::cout << "player " << playerNumber << " choose a field:" << std::endl;
|
||||||
std::cin >> chosenField;
|
std::cin >> chosenField;
|
||||||
}while(field[chosenField] != 0);
|
} while (field[chosenField] != 0);
|
||||||
return chosenField;
|
return chosenField;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool vertical(unsigned int playerNumber, std::vector<unsigned int> &field)
|
bool vertical(unsigned int playerNumber, std::vector<unsigned int> &field) {
|
||||||
{
|
if ((field[0] == playerNumber && field[1] == playerNumber &&
|
||||||
if((field[0] == playerNumber && field[1] == playerNumber && field[2] == playerNumber)
|
field[2] == playerNumber) ||
|
||||||
|| (field[3] == playerNumber && field[4] == playerNumber && field[5] == playerNumber)
|
(field[3] == playerNumber && field[4] == playerNumber &&
|
||||||
|| (field[6] == playerNumber && field[7] == playerNumber && field[8] == playerNumber))
|
field[5] == playerNumber) ||
|
||||||
{
|
(field[6] == playerNumber && field[7] == playerNumber &&
|
||||||
|
field[8] == playerNumber)) {
|
||||||
return 1;
|
return 1;
|
||||||
}else return 0;
|
} else
|
||||||
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool horizontal(unsigned int playerNumber, std::vector<unsigned int> &field)
|
bool horizontal(unsigned int playerNumber, std::vector<unsigned int> &field) {
|
||||||
{
|
if ((field[0] == playerNumber && field[3] == playerNumber &&
|
||||||
if((field[0] == playerNumber && field[3] == playerNumber && field[6] == playerNumber)
|
field[6] == playerNumber) ||
|
||||||
|| (field[1] == playerNumber && field[4] == playerNumber && field[7] == playerNumber)
|
(field[1] == playerNumber && field[4] == playerNumber &&
|
||||||
|| (field[2] == playerNumber && field[5] == playerNumber && field[8] == playerNumber))
|
field[7] == playerNumber) ||
|
||||||
{
|
(field[2] == playerNumber && field[5] == playerNumber &&
|
||||||
|
field[8] == playerNumber)) {
|
||||||
return 1;
|
return 1;
|
||||||
}else return 0;
|
} else
|
||||||
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool across(unsigned int playerNumber, std::vector<unsigned int> &field)
|
bool across(unsigned int playerNumber, std::vector<unsigned int> &field) {
|
||||||
{
|
if ((field[0] == playerNumber && field[4] == playerNumber &&
|
||||||
if((field[0] == playerNumber && field[4] == playerNumber && field[8] == playerNumber)
|
field[8] == playerNumber) ||
|
||||||
|| (field[2] == playerNumber && field[4] == playerNumber && field[6] == playerNumber))
|
(field[2] == playerNumber && field[4] == playerNumber &&
|
||||||
{
|
field[6] == playerNumber)) {
|
||||||
return 1;
|
return 1;
|
||||||
}else return 0;
|
} else
|
||||||
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool checkPlayerWin(unsigned int playerNumber, std::vector<unsigned int> &field)
|
bool checkPlayerWin(unsigned int playerNumber,
|
||||||
{
|
std::vector<unsigned int> &field) {
|
||||||
if(vertical(playerNumber, field)) return 1;
|
if (vertical(playerNumber, field))
|
||||||
if(horizontal(playerNumber, field)) return 1;
|
return 1;
|
||||||
if(across(playerNumber, field)) return 1;
|
if (horizontal(playerNumber, field))
|
||||||
else return 0;
|
return 1;
|
||||||
|
if (across(playerNumber, field))
|
||||||
|
return 1;
|
||||||
|
else
|
||||||
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
unsigned int checkIfWin(std::vector<unsigned int> &field)
|
unsigned int checkIfWin(std::vector<unsigned int> &field) {
|
||||||
{
|
if (checkPlayerWin(1, field))
|
||||||
if(checkPlayerWin(1, field)) return 1;
|
return 1;
|
||||||
else if(checkPlayerWin(2, field)) return 2;
|
else if (checkPlayerWin(2, field))
|
||||||
else return 0;
|
return 2;
|
||||||
|
else
|
||||||
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool checkIfFilled(std::vector<unsigned int> &field)
|
bool checkIfFilled(std::vector<unsigned int> &field) {
|
||||||
{
|
|
||||||
bool filled = 1;
|
bool filled = 1;
|
||||||
for(int i = 0; i < 9; i++)
|
for (int i = 0; i < 9; i++) {
|
||||||
{
|
if (field[i] == 0) {
|
||||||
if(field[i] == 0)
|
|
||||||
{
|
|
||||||
filled = 0;
|
filled = 0;
|
||||||
return filled;
|
return filled;
|
||||||
}
|
}
|
||||||
@ -84,28 +92,32 @@ bool checkIfFilled(std::vector<unsigned int> &field)
|
|||||||
return filled;
|
return filled;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool turn(unsigned int playerNumber, std::vector<unsigned int> &field, bool *filled, unsigned int *whoWon)
|
bool turn(unsigned int playerNumber, std::vector<unsigned int> &field,
|
||||||
{
|
bool *filled, unsigned int *whoWon) {
|
||||||
field[chooseField(playerNumber, field)] = playerNumber;
|
field[chooseField(playerNumber, field)] = playerNumber;
|
||||||
printField(field);
|
printField(field);
|
||||||
*whoWon = checkIfWin(field);
|
*whoWon = checkIfWin(field);
|
||||||
*filled = checkIfFilled(field);
|
*filled = checkIfFilled(field);
|
||||||
if(*whoWon != 0 || *filled != 0) return 1;
|
if (*whoWon != 0 || *filled != 0)
|
||||||
else return 0;
|
return 1;
|
||||||
|
else
|
||||||
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
int main()
|
int main() {
|
||||||
{
|
|
||||||
std::vector<unsigned int> field = {0, 0, 0, 0, 0, 0, 0, 0, 0};
|
std::vector<unsigned int> field = {0, 0, 0, 0, 0, 0, 0, 0, 0};
|
||||||
unsigned int whoWon = 0;
|
unsigned int whoWon = 0;
|
||||||
bool filled = 0;
|
bool filled = 0;
|
||||||
|
|
||||||
while(whoWon == 0 || filled == 0)
|
while (whoWon == 0 || filled == 0) {
|
||||||
{
|
if (turn(1, field, &filled, &whoWon))
|
||||||
if(turn(1, field, &filled, &whoWon)) break;
|
break;
|
||||||
if(turn(2, field, &filled, &whoWon)) break;
|
if (turn(2, field, &filled, &whoWon))
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
if(!filled) std::cout << "Player " << whoWon << " Won!" << std::endl;
|
if (!filled)
|
||||||
else std::cout << "DRAW!" << std::endl;
|
std::cout << "Player " << whoWon << " Won!" << std::endl;
|
||||||
|
else
|
||||||
|
std::cout << "DRAW!" << std::endl;
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -2,18 +2,14 @@
|
|||||||
#include <string>
|
#include <string>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
const std::vector <std::string> TIERS = {"Abhorrent", "Bad", "Mid", "Good", "Top", "God Tier"};
|
const std::vector<std::string> TIERS = {"Abhorrent", "Bad", "Mid",
|
||||||
|
"Good", "Top", "God Tier"};
|
||||||
const float TIER_BASE = TIERS.size();
|
const float TIER_BASE = TIERS.size();
|
||||||
|
|
||||||
void print(std::string const s)
|
void print(std::string const s) { std::cout << s << std::endl; }
|
||||||
{
|
|
||||||
std::cout << s << std::endl;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool errorUserInput(std::string userInput)
|
bool errorUserInput(std::string userInput) {
|
||||||
{
|
if (userInput.find("/") == std::string::npos) {
|
||||||
if(userInput.find("/") == std::string::npos)
|
|
||||||
{
|
|
||||||
print("No '/' was found!");
|
print("No '/' was found!");
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
@ -21,27 +17,23 @@ bool errorUserInput(std::string userInput)
|
|||||||
size_t positionOfSlash = userInput.find("/");
|
size_t positionOfSlash = userInput.find("/");
|
||||||
std::string nominatorS = userInput.substr(0, positionOfSlash);
|
std::string nominatorS = userInput.substr(0, positionOfSlash);
|
||||||
|
|
||||||
try
|
try {
|
||||||
{
|
|
||||||
float nominator = stof(nominatorS);
|
float nominator = stof(nominatorS);
|
||||||
}catch ( std::invalid_argument )
|
} catch (std::invalid_argument) {
|
||||||
{
|
|
||||||
print("No number was found before the slash!");
|
print("No number was found before the slash!");
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::string denominatorS = userInput.substr(positionOfSlash + 1, userInput.length() - 1);
|
std::string denominatorS =
|
||||||
|
userInput.substr(positionOfSlash + 1, userInput.length() - 1);
|
||||||
|
|
||||||
try
|
try {
|
||||||
{
|
|
||||||
float denominator = stof(denominatorS);
|
float denominator = stof(denominatorS);
|
||||||
if(denominator == 0)
|
if (denominator == 0) {
|
||||||
{
|
|
||||||
print("You cannot divide by 0!");
|
print("You cannot divide by 0!");
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
}catch ( std::invalid_argument )
|
} catch (std::invalid_argument) {
|
||||||
{
|
|
||||||
print("No number was found after the slash!");
|
print("No number was found after the slash!");
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
@ -49,39 +41,33 @@ bool errorUserInput(std::string userInput)
|
|||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::string convertToTier(float nominator, float denominator)
|
std::string convertToTier(float nominator, float denominator) {
|
||||||
{
|
|
||||||
float fraction = nominator / denominator;
|
float fraction = nominator / denominator;
|
||||||
int tierIndex;
|
int tierIndex;
|
||||||
for(int i = TIER_BASE; i > 0; i--)
|
for (int i = TIER_BASE; i > 0; i--) {
|
||||||
{
|
if (fraction >= (i / TIER_BASE)) {
|
||||||
if(fraction >= ( i / TIER_BASE))
|
|
||||||
{
|
|
||||||
tierIndex = i - 1;
|
tierIndex = i - 1;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if(tierIndex == 0 & fraction > (1.1/10.0)) return TIERS[1];
|
if (tierIndex == 0 & fraction > (1.1 / 10.0))
|
||||||
|
return TIERS[1];
|
||||||
return TIERS[tierIndex];
|
return TIERS[tierIndex];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
int main() {
|
||||||
int main()
|
|
||||||
{
|
|
||||||
std::string userScore;
|
std::string userScore;
|
||||||
do
|
do {
|
||||||
{
|
|
||||||
print("Enter your score in a format: numberOne/numberTwo");
|
print("Enter your score in a format: numberOne/numberTwo");
|
||||||
getline(std::cin, userScore);
|
getline(std::cin, userScore);
|
||||||
}while(errorUserInput(userScore));
|
} while (errorUserInput(userScore));
|
||||||
|
|
||||||
size_t positionOfSlash = userScore.find("/");
|
size_t positionOfSlash = userScore.find("/");
|
||||||
std::string nominatorS = userScore.substr(0, positionOfSlash);
|
std::string nominatorS = userScore.substr(0, positionOfSlash);
|
||||||
|
|
||||||
|
|
||||||
float nominator = stof(nominatorS);
|
float nominator = stof(nominatorS);
|
||||||
std::string denominatorS = userScore.substr(positionOfSlash + 1, userScore.length() - 1);
|
std::string denominatorS =
|
||||||
|
userScore.substr(positionOfSlash + 1, userScore.length() - 1);
|
||||||
|
|
||||||
float denominator = stof(denominatorS);
|
float denominator = stof(denominatorS);
|
||||||
print(convertToTier(nominator, denominator));
|
print(convertToTier(nominator, denominator));
|
||||||
|
|||||||
@ -1,10 +1,8 @@
|
|||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
|
|
||||||
int main()
|
int main() {
|
||||||
{
|
|
||||||
int x = 10;
|
int x = 10;
|
||||||
while (x-- > 0)
|
while (x-- > 0) {
|
||||||
{
|
|
||||||
printf("%d;", x);
|
printf("%d;", x);
|
||||||
}
|
}
|
||||||
return 0;
|
return 0;
|
||||||
|
|||||||
@ -2,21 +2,22 @@
|
|||||||
#include <iostream>
|
#include <iostream>
|
||||||
#include <random>
|
#include <random>
|
||||||
|
|
||||||
int main()
|
int main() {
|
||||||
{
|
const int nrolls = 10000;
|
||||||
const int nrolls=10000;
|
|
||||||
|
|
||||||
std::random_device rd;
|
std::random_device rd;
|
||||||
std::mt19937 gen(rd());
|
std::mt19937 gen(rd());
|
||||||
std::bernoulli_distribution distribution(0.5);
|
std::bernoulli_distribution distribution(0.5);
|
||||||
|
|
||||||
int count=0; // count number of trues
|
int count = 0; // count number of trues
|
||||||
|
|
||||||
for (int i=0; i<nrolls; ++i) if (distribution(gen)) ++count;
|
for (int i = 0; i < nrolls; ++i)
|
||||||
|
if (distribution(gen))
|
||||||
|
++count;
|
||||||
|
|
||||||
std::cout << "bernoulli_distribution (0.5) x 10000:" << std::endl;
|
std::cout << "bernoulli_distribution (0.5) x 10000:" << std::endl;
|
||||||
std::cout << "true: " << count << std::endl;
|
std::cout << "true: " << count << std::endl;
|
||||||
std::cout << "false: " << nrolls-count << std::endl;
|
std::cout << "false: " << nrolls - count << std::endl;
|
||||||
|
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,13 +1,14 @@
|
|||||||
#include <random>
|
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
|
#include <random>
|
||||||
|
|
||||||
int main() {
|
int main() {
|
||||||
std::random_device rd;
|
std::random_device rd;
|
||||||
std::mt19937 gen(rd());
|
std::mt19937 gen(rd());
|
||||||
std::uniform_real_distribution<> dis(0, 1);
|
std::uniform_real_distribution<> dis(0, 1);
|
||||||
|
|
||||||
for(int i = 0; i < 10; i++) {
|
for (int i = 0; i < 10; i++) {
|
||||||
|
|
||||||
std::cout << dis(gen) << std::endl;
|
std::cout << dis(gen) << std::endl;
|
||||||
}return 0;
|
}
|
||||||
|
return 0;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -8,120 +8,117 @@ const bool BOT_WON = 0;
|
|||||||
const bool PLAYER_WON = 1;
|
const bool PLAYER_WON = 1;
|
||||||
const int NOBODY_WON = 2;
|
const int NOBODY_WON = 2;
|
||||||
|
|
||||||
void print(std::string const s)
|
void print(std::string const s) { std::cout << s << std::endl; }
|
||||||
{
|
|
||||||
std::cout << s << std::endl;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool validSequence(std::string const s)
|
bool validSequence(std::string const s) {
|
||||||
{
|
if (s.size() != SEQUENCE_LENGTH) {
|
||||||
if(s.size() != SEQUENCE_LENGTH)
|
|
||||||
{
|
|
||||||
print("Sequence too long");
|
print("Sequence too long");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
if( (s[0] != 'B' && s[0] != 'R') ||
|
if ((s[0] != 'B' && s[0] != 'R') || (s[1] != 'B' && s[1] != 'R') ||
|
||||||
(s[1] != 'B' && s[1] != 'R') ||
|
(s[2] != 'B' && s[2] != 'R')) {
|
||||||
(s[2] != 'B' && s[2] != 'R'))
|
|
||||||
{
|
|
||||||
print("Sequence consists of illegal signs!");
|
print("Sequence consists of illegal signs!");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::string playerChoice()
|
std::string playerChoice() {
|
||||||
{
|
|
||||||
std::string playerSequence;
|
std::string playerSequence;
|
||||||
do
|
do {
|
||||||
{
|
|
||||||
std::cin >> playerSequence;
|
std::cin >> playerSequence;
|
||||||
}
|
} while (!validSequence(playerSequence));
|
||||||
while(!validSequence(playerSequence));
|
|
||||||
return playerSequence;
|
return playerSequence;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::string botChoice(std::string const playerSequence)
|
std::string botChoice(std::string const playerSequence) {
|
||||||
{
|
|
||||||
std::string botSequence;
|
std::string botSequence;
|
||||||
if(playerSequence[1] == 'B') botSequence.push_back('R');
|
if (playerSequence[1] == 'B')
|
||||||
else botSequence.push_back('B');
|
botSequence.push_back('R');
|
||||||
|
else
|
||||||
|
botSequence.push_back('B');
|
||||||
botSequence.push_back(playerSequence[0]);
|
botSequence.push_back(playerSequence[0]);
|
||||||
botSequence.push_back(playerSequence[2]);
|
botSequence.push_back(playerSequence[2]);
|
||||||
return botSequence;
|
return botSequence;
|
||||||
}
|
}
|
||||||
|
|
||||||
int compareGeneratedAndPlayers(std::string playerSequence, std::string botSequence, std::string generatedSequence)
|
int compareGeneratedAndPlayers(std::string playerSequence,
|
||||||
{
|
std::string botSequence,
|
||||||
|
std::string generatedSequence) {
|
||||||
int generatedSequenceLength = generatedSequence.length();
|
int generatedSequenceLength = generatedSequence.length();
|
||||||
std::string sequenceToCompare = generatedSequence.substr(generatedSequenceLength - SEQUENCE_LENGTH, generatedSequenceLength);
|
std::string sequenceToCompare = generatedSequence.substr(
|
||||||
if(sequenceToCompare.compare(playerSequence) == 0) return PLAYER_WON;
|
generatedSequenceLength - SEQUENCE_LENGTH, generatedSequenceLength);
|
||||||
if(sequenceToCompare.compare(botSequence) == 0) return BOT_WON;
|
if (sequenceToCompare.compare(playerSequence) == 0)
|
||||||
else return NOBODY_WON;
|
return PLAYER_WON;
|
||||||
|
if (sequenceToCompare.compare(botSequence) == 0)
|
||||||
|
return BOT_WON;
|
||||||
|
else
|
||||||
|
return NOBODY_WON;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool game(std::string playerSequence, std::string botSequence)
|
bool game(std::string playerSequence, std::string botSequence) {
|
||||||
{
|
|
||||||
std::string generatedSequence;
|
std::string generatedSequence;
|
||||||
std::random_device rd;
|
std::random_device rd;
|
||||||
std::mt19937 gen(rd());
|
std::mt19937 gen(rd());
|
||||||
std::bernoulli_distribution distribution(0.5);
|
std::bernoulli_distribution distribution(0.5);
|
||||||
for(int i = 0; i < SEQUENCE_LENGTH; i++)
|
for (int i = 0; i < SEQUENCE_LENGTH; i++) {
|
||||||
{
|
if (distribution(gen))
|
||||||
if(distribution(gen)) generatedSequence.push_back('R');
|
generatedSequence.push_back('R');
|
||||||
else generatedSequence.push_back('B');
|
else
|
||||||
|
generatedSequence.push_back('B');
|
||||||
}
|
}
|
||||||
|
|
||||||
while(compareGeneratedAndPlayers(playerSequence, botSequence, generatedSequence) == NOBODY_WON)
|
while (compareGeneratedAndPlayers(playerSequence, botSequence,
|
||||||
{
|
generatedSequence) == NOBODY_WON) {
|
||||||
if(distribution(gen)) generatedSequence.push_back('R');
|
if (distribution(gen))
|
||||||
else generatedSequence.push_back('B');
|
generatedSequence.push_back('R');
|
||||||
|
else
|
||||||
|
generatedSequence.push_back('B');
|
||||||
}
|
}
|
||||||
|
|
||||||
print(generatedSequence);
|
print(generatedSequence);
|
||||||
if(compareGeneratedAndPlayers(playerSequence, botSequence, generatedSequence) == PLAYER_WON) return PLAYER_WON;
|
if (compareGeneratedAndPlayers(playerSequence, botSequence,
|
||||||
else return BOT_WON;
|
generatedSequence) == PLAYER_WON)
|
||||||
|
return PLAYER_WON;
|
||||||
|
else
|
||||||
|
return BOT_WON;
|
||||||
}
|
}
|
||||||
|
|
||||||
void score(int playerWins, int botWins)
|
void score(int playerWins, int botWins) {
|
||||||
{
|
|
||||||
std::cout << "Player won: " << playerWins << " times!" << std::endl;
|
std::cout << "Player won: " << playerWins << " times!" << std::endl;
|
||||||
std::cout << "Bot won: " << botWins << " times!" << std::endl;
|
std::cout << "Bot won: " << botWins << " times!" << std::endl;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
int main() {
|
||||||
|
|
||||||
int main()
|
|
||||||
{
|
|
||||||
int playerWins = 0;
|
int playerWins = 0;
|
||||||
int botWins = 0;
|
int botWins = 0;
|
||||||
do
|
do {
|
||||||
{
|
|
||||||
print("Do you want to play the game? 1 - yes, 0 - no");
|
print("Do you want to play the game? 1 - yes, 0 - no");
|
||||||
bool continue_ = 1;
|
bool continue_ = 1;
|
||||||
std::string playerInput;
|
std::string playerInput;
|
||||||
std::cin >> playerInput;
|
std::cin >> playerInput;
|
||||||
if(playerInput[0] == '1') continue_ = 1;
|
if (playerInput[0] == '1')
|
||||||
else continue_ = 0;
|
continue_ = 1;
|
||||||
if(!continue_) break;
|
else
|
||||||
|
continue_ = 0;
|
||||||
|
if (!continue_)
|
||||||
|
break;
|
||||||
std::string playerSequence;
|
std::string playerSequence;
|
||||||
print("Write three colors sequence created from 52 cards from the deck (26 Black, 26 Red), write B for Black and R for Red");
|
print("Write three colors sequence created from 52 cards from the deck (26 "
|
||||||
|
"Black, 26 Red), write B for Black and R for Red");
|
||||||
playerSequence = playerChoice();
|
playerSequence = playerChoice();
|
||||||
std::string botSequence = botChoice(playerSequence);
|
std::string botSequence = botChoice(playerSequence);
|
||||||
print("Bot has chosen this sequence:");
|
print("Bot has chosen this sequence:");
|
||||||
print(botSequence);
|
print(botSequence);
|
||||||
if(game(playerSequence, botSequence))
|
if (game(playerSequence, botSequence)) {
|
||||||
{
|
|
||||||
print("You won!");
|
print("You won!");
|
||||||
playerWins++;
|
playerWins++;
|
||||||
score(playerWins, botWins);
|
score(playerWins, botWins);
|
||||||
}
|
} else {
|
||||||
else
|
|
||||||
{
|
|
||||||
print("Bot won!");
|
print("Bot won!");
|
||||||
botWins++;
|
botWins++;
|
||||||
score(playerWins, botWins);
|
score(playerWins, botWins);
|
||||||
}
|
}
|
||||||
}while(1);
|
} while (1);
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,8 +1,7 @@
|
|||||||
#include <iostream>
|
#include <iostream>
|
||||||
|
|
||||||
int main()
|
int main() {
|
||||||
{
|
float X = 1 / 2;
|
||||||
float X = 1/2;
|
|
||||||
std::cout << X << std::endl;
|
std::cout << X << std::endl;
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -83,8 +83,8 @@ export function useBattery() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
setLoading(false)
|
setLoading(false)
|
||||||
} catch (e: any) {
|
} catch (e: unknown) {
|
||||||
setError(e?.message ?? 'Failed to read battery status')
|
setError(e instanceof Error ? e.message : 'Failed to read battery status')
|
||||||
setLoading(false)
|
setLoading(false)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -10,7 +10,7 @@ const API_BASE = 'https://api.football-data.org/v4';
|
|||||||
const API_TOKEN = process.env.FOOTBALL_DATA_API_KEY;
|
const API_TOKEN = process.env.FOOTBALL_DATA_API_KEY;
|
||||||
|
|
||||||
if (!API_TOKEN) {
|
if (!API_TOKEN) {
|
||||||
// eslint-disable-next-line no-console
|
|
||||||
console.warn('[server] FOOTBALL_DATA_API_KEY is not set. Live data will not work until you set it.');
|
console.warn('[server] FOOTBALL_DATA_API_KEY is not set. Live data will not work until you set it.');
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -32,34 +32,40 @@ app.use((req, res, next) => {
|
|||||||
const clip = (s: string) => (s && s.length > MAX_LOG_BODY ? `${s.slice(0, MAX_LOG_BODY)}…(+${s.length - MAX_LOG_BODY})` : s);
|
const clip = (s: string) => (s && s.length > MAX_LOG_BODY ? `${s.slice(0, MAX_LOG_BODY)}…(+${s.length - MAX_LOG_BODY})` : s);
|
||||||
|
|
||||||
// Attach id so downstream handlers could use it if needed
|
// Attach id so downstream handlers could use it if needed
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
(res as any).locals = { ...(res as any).locals, requestId: id };
|
(res as any).locals = { ...(res as any).locals, requestId: id };
|
||||||
|
|
||||||
// Patch res.json and res.send to capture response payload
|
// Patch res.json and res.send to capture response payload
|
||||||
const originalJson = res.json.bind(res);
|
const originalJson = res.json.bind(res);
|
||||||
const originalSend = res.send.bind(res);
|
const originalSend = res.send.bind(res);
|
||||||
(res as any).json = (body: any) => {
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
(res as any).json = (body: unknown) => {
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
try { (res as any).locals.bodyForLog = body; } catch { /* ignore */ }
|
try { (res as any).locals.bodyForLog = body; } catch { /* ignore */ }
|
||||||
return originalJson(body);
|
return originalJson(body);
|
||||||
};
|
};
|
||||||
(res as any).send = (body: any) => {
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
(res as any).send = (body: unknown) => {
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
try { (res as any).locals.bodyForLog = body; } catch { /* ignore */ }
|
try { (res as any).locals.bodyForLog = body; } catch { /* ignore */ }
|
||||||
return originalSend(body as any);
|
return originalSend(body);
|
||||||
};
|
};
|
||||||
|
|
||||||
// eslint-disable-next-line no-console
|
|
||||||
console.log(`[#${id}] -> ${req.method} ${req.originalUrl}` + (Object.keys(req.query || {}).length ? ` query=${JSON.stringify(req.query)}` : ''));
|
console.log(`[#${id}] -> ${req.method} ${req.originalUrl}` + (Object.keys(req.query || {}).length ? ` query=${JSON.stringify(req.query)}` : ''));
|
||||||
|
|
||||||
res.on('finish', () => {
|
res.on('finish', () => {
|
||||||
const durMs = Number(process.hrtime.bigint() - start) / 1_000_000;
|
const durMs = Number(process.hrtime.bigint() - start) / 1_000_000;
|
||||||
let bodyPreview = '';
|
let bodyPreview = '';
|
||||||
try {
|
try {
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
const body = (res as any).locals?.bodyForLog;
|
const body = (res as any).locals?.bodyForLog;
|
||||||
if (body !== undefined) {
|
if (body !== undefined) {
|
||||||
const str = typeof body === 'string' ? body : JSON.stringify(body);
|
const str = typeof body === 'string' ? body : JSON.stringify(body);
|
||||||
bodyPreview = ` body=${clip(str)}`;
|
bodyPreview = ` body=${clip(str)}`;
|
||||||
}
|
}
|
||||||
} catch { /* ignore */ }
|
} catch { /* ignore */ }
|
||||||
// eslint-disable-next-line no-console
|
|
||||||
console.log(`[#${id}] <- ${req.method} ${req.originalUrl} ${res.statusCode} ${durMs.toFixed(1)}ms${bodyPreview}`);
|
console.log(`[#${id}] <- ${req.method} ${req.originalUrl} ${res.statusCode} ${durMs.toFixed(1)}ms${bodyPreview}`);
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -69,13 +75,14 @@ app.use((req, res, next) => {
|
|||||||
// Axios interceptors to log outgoing requests and incoming responses
|
// Axios interceptors to log outgoing requests and incoming responses
|
||||||
axios.interceptors.request.use(
|
axios.interceptors.request.use(
|
||||||
(config) => {
|
(config) => {
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
(config as any).metadata = { start: Date.now() };
|
(config as any).metadata = { start: Date.now() };
|
||||||
// eslint-disable-next-line no-console
|
|
||||||
console.log(`[axios ->] ${String(config.method || 'GET').toUpperCase()} ${config.url}`);
|
console.log(`[axios ->] ${String(config.method || 'GET').toUpperCase()} ${config.url}`);
|
||||||
return config;
|
return config;
|
||||||
},
|
},
|
||||||
(error) => {
|
(error) => {
|
||||||
// eslint-disable-next-line no-console
|
|
||||||
console.warn('[axios req error]', error?.message || error);
|
console.warn('[axios req error]', error?.message || error);
|
||||||
return Promise.reject(error);
|
return Promise.reject(error);
|
||||||
}
|
}
|
||||||
@ -83,6 +90,7 @@ axios.interceptors.request.use(
|
|||||||
|
|
||||||
axios.interceptors.response.use(
|
axios.interceptors.response.use(
|
||||||
(response) => {
|
(response) => {
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
const started = (response.config as any).metadata?.start || Date.now();
|
const started = (response.config as any).metadata?.start || Date.now();
|
||||||
const dur = Date.now() - started;
|
const dur = Date.now() - started;
|
||||||
let dataStr = '';
|
let dataStr = '';
|
||||||
@ -92,12 +100,13 @@ axios.interceptors.response.use(
|
|||||||
const size = dataStr?.length || 0;
|
const size = dataStr?.length || 0;
|
||||||
const MAX_LOG_BODY = 2000;
|
const MAX_LOG_BODY = 2000;
|
||||||
const clip = (s: string) => (s && s.length > MAX_LOG_BODY ? `${s.slice(0, MAX_LOG_BODY)}…(+${s.length - MAX_LOG_BODY})` : s);
|
const clip = (s: string) => (s && s.length > MAX_LOG_BODY ? `${s.slice(0, MAX_LOG_BODY)}…(+${s.length - MAX_LOG_BODY})` : s);
|
||||||
// eslint-disable-next-line no-console
|
|
||||||
console.log(`[axios <-] ${response.status} ${String(response.config.method || 'GET').toUpperCase()} ${response.config.url} ${dur}ms ~${size}B data=${clip(dataStr)}`);
|
console.log(`[axios <-] ${response.status} ${String(response.config.method || 'GET').toUpperCase()} ${response.config.url} ${dur}ms ~${size}B data=${clip(dataStr)}`);
|
||||||
return response;
|
return response;
|
||||||
},
|
},
|
||||||
(error) => {
|
(error) => {
|
||||||
const cfg = error?.config || {};
|
const cfg = error?.config || {};
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
const started = (cfg as any).metadata?.start || Date.now();
|
const started = (cfg as any).metadata?.start || Date.now();
|
||||||
const dur = Date.now() - started;
|
const dur = Date.now() - started;
|
||||||
const status = error?.response?.status;
|
const status = error?.response?.status;
|
||||||
@ -108,7 +117,7 @@ axios.interceptors.response.use(
|
|||||||
} catch { /* ignore */ }
|
} catch { /* ignore */ }
|
||||||
const MAX_LOG_BODY = 2000;
|
const MAX_LOG_BODY = 2000;
|
||||||
const clip = (s: string) => (s && s.length > MAX_LOG_BODY ? `${s.slice(0, MAX_LOG_BODY)}…(+${s.length - MAX_LOG_BODY})` : s);
|
const clip = (s: string) => (s && s.length > MAX_LOG_BODY ? `${s.slice(0, MAX_LOG_BODY)}…(+${s.length - MAX_LOG_BODY})` : s);
|
||||||
// eslint-disable-next-line no-console
|
|
||||||
console.warn(`[axios ! ] ${status ?? 'ERR'} ${String(cfg.method || 'GET').toUpperCase()} ${cfg.url} ${dur}ms data=${dataStr ? clip(dataStr) : (error?.message || 'error')}`);
|
console.warn(`[axios ! ] ${status ?? 'ERR'} ${String(cfg.method || 'GET').toUpperCase()} ${cfg.url} ${dur}ms data=${dataStr ? clip(dataStr) : (error?.message || 'error')}`);
|
||||||
return Promise.reject(error);
|
return Promise.reject(error);
|
||||||
}
|
}
|
||||||
@ -122,7 +131,8 @@ function buildHeaders() {
|
|||||||
} as Record<string, string>;
|
} as Record<string, string>;
|
||||||
}
|
}
|
||||||
|
|
||||||
function normalizeMatch(m: any) {
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
function normalizeMatch(m: Record<string, any>) {
|
||||||
return {
|
return {
|
||||||
id: m.id,
|
id: m.id,
|
||||||
utcDate: m.utcDate,
|
utcDate: m.utcDate,
|
||||||
@ -135,7 +145,8 @@ function normalizeMatch(m: any) {
|
|||||||
score: m.score,
|
score: m.score,
|
||||||
competition: m.competition?.name || 'UEFA Champions League',
|
competition: m.competition?.name || 'UEFA Champions League',
|
||||||
venue: m.venue,
|
venue: m.venue,
|
||||||
referees: m.referees?.map((r: any) => r.name).filter(Boolean) || [],
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
referees: m.referees?.map((r: Record<string, any>) => r.name).filter(Boolean) || [],
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -160,9 +171,10 @@ app.get('/api/live', async (_req: Request, res: Response) => {
|
|||||||
const { data } = await axios.get(url, { headers: buildHeaders(), params: { status: 'LIVE' } });
|
const { data } = await axios.get(url, { headers: buildHeaders(), params: { status: 'LIVE' } });
|
||||||
const matches = (data.matches || []).map(normalizeMatch);
|
const matches = (data.matches || []).map(normalizeMatch);
|
||||||
res.json({ count: matches.length, matches, fetchedAt: new Date().toISOString() });
|
res.json({ count: matches.length, matches, fetchedAt: new Date().toISOString() });
|
||||||
} catch (err: any) {
|
} catch (err: unknown) {
|
||||||
const status = err?.response?.status || 500;
|
const axErr = err as { response?: { status?: number; data?: unknown }; message?: string };
|
||||||
res.status(status).json({ error: 'Failed to fetch live matches', details: err?.response?.data || err?.message });
|
const status = axErr?.response?.status || 500;
|
||||||
|
res.status(status).json({ error: 'Failed to fetch live matches', details: axErr?.response?.data || axErr?.message });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -191,13 +203,14 @@ app.get('/api/matches', async (req: Request, res: Response) => {
|
|||||||
});
|
});
|
||||||
const matches = (data.matches || []).map(normalizeMatch);
|
const matches = (data.matches || []).map(normalizeMatch);
|
||||||
res.json({ count: matches.length, matches, fetchedAt: new Date().toISOString() });
|
res.json({ count: matches.length, matches, fetchedAt: new Date().toISOString() });
|
||||||
} catch (err: any) {
|
} catch (err: unknown) {
|
||||||
const status = err?.response?.status || 500;
|
const axErr = err as { response?: { status?: number; data?: unknown }; message?: string };
|
||||||
res.status(status).json({ error: 'Failed to fetch matches', details: err?.response?.data || err?.message });
|
const status = axErr?.response?.status || 500;
|
||||||
|
res.status(status).json({ error: 'Failed to fetch matches', details: axErr?.response?.data || axErr?.message });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
app.listen(PORT, () => {
|
app.listen(PORT, () => {
|
||||||
// eslint-disable-next-line no-console
|
|
||||||
console.log(`[server] Listening on http://localhost:${PORT}`);
|
console.log(`[server] Listening on http://localhost:${PORT}`);
|
||||||
});
|
});
|
||||||
|
|||||||
@ -27,7 +27,7 @@ type ApiResponse = {
|
|||||||
fetchedAt: string;
|
fetchedAt: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
function useFetchOnce<T>(fn: () => Promise<T>) {
|
function _useFetchOnce<T>(fn: () => Promise<T>) {
|
||||||
const [data, setData] = useState<T | null>(null);
|
const [data, setData] = useState<T | null>(null);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const [loading, setLoading] = useState<boolean>(true);
|
const [loading, setLoading] = useState<boolean>(true);
|
||||||
@ -41,8 +41,8 @@ function useFetchOnce<T>(fn: () => Promise<T>) {
|
|||||||
setData(result);
|
setData(result);
|
||||||
setError(null);
|
setError(null);
|
||||||
}
|
}
|
||||||
} catch (e: any) {
|
} catch (e: unknown) {
|
||||||
if (mounted) setError(e?.message || 'Failed to fetch');
|
if (mounted) setError(e instanceof Error ? e.message : 'Failed to fetch');
|
||||||
} finally {
|
} finally {
|
||||||
if (mounted) setLoading(false);
|
if (mounted) setLoading(false);
|
||||||
}
|
}
|
||||||
@ -57,14 +57,13 @@ async function fetchJson<T>(url: string, init?: RequestInit): Promise<T> {
|
|||||||
const res = await fetch(url, { cache: 'no-store', ...init });
|
const res = await fetch(url, { cache: 'no-store', ...init });
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
const text = await res.text();
|
const text = await res.text();
|
||||||
let body: any = null;
|
let body: unknown = null;
|
||||||
try { body = text ? JSON.parse(text) : null; } catch { /* noop */ }
|
try { body = text ? JSON.parse(text) : null; } catch { /* noop */ }
|
||||||
const err: any = new Error(`HTTP ${res.status}`);
|
const err: { message: string; status: number; body: unknown; waitSec?: number } = { message: `HTTP ${res.status}`, status: res.status, body };
|
||||||
err.status = res.status;
|
|
||||||
err.body = body;
|
|
||||||
// Try to derive wait seconds for 429 from body.details.message like: "You reached your request limit. Wait 56 seconds."
|
// Try to derive wait seconds for 429 from body.details.message like: "You reached your request limit. Wait 56 seconds."
|
||||||
if (res.status === 429) {
|
if (res.status === 429) {
|
||||||
const msg: string | undefined = body?.details?.message || body?.message || body?.error;
|
const details = body as Record<string, unknown> | null;
|
||||||
|
const msg: string | undefined = (details?.message as string) || (details?.error as string) || (details?.details as Record<string, unknown>)?.message as string | undefined;
|
||||||
const m = msg ? msg.match(/(\d+)\s*seconds?/) : null;
|
const m = msg ? msg.match(/(\d+)\s*seconds?/) : null;
|
||||||
if (m) err.waitSec = Number(m[1]);
|
if (m) err.waitSec = Number(m[1]);
|
||||||
}
|
}
|
||||||
@ -143,18 +142,19 @@ function useBackoffUntilSuccess<T>(fn: () => Promise<T>, opts?: { baseDelaySec?:
|
|||||||
clearTimers();
|
clearTimers();
|
||||||
setData(result);
|
setData(result);
|
||||||
setError(null);
|
setError(null);
|
||||||
} catch (e: any) {
|
} catch (e: unknown) {
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
|
const httpErr = e as { status?: number; waitSec?: number; message?: string };
|
||||||
// 429: backoff and retry
|
// 429: backoff and retry
|
||||||
if (e?.status === 429) {
|
if (httpErr?.status === 429) {
|
||||||
const suggested = Number(e?.waitSec) || delayRef.current || base;
|
const suggested = Number(httpErr?.waitSec) || delayRef.current || base;
|
||||||
const next = Math.min(max, Math.max(base, suggested));
|
const next = Math.min(max, Math.max(base, suggested));
|
||||||
delayRef.current = Math.min(max, Math.ceil(next * factor));
|
delayRef.current = Math.min(max, Math.ceil(next * factor));
|
||||||
setError(`Rate limited. Retrying in ${next}s...`);
|
setError(`Rate limited. Retrying in ${next}s...`);
|
||||||
scheduleRetry(next);
|
scheduleRetry(next);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
setError(e?.message || 'Failed to fetch');
|
setError(httpErr?.message || 'Failed to fetch');
|
||||||
} finally {
|
} finally {
|
||||||
inFlightRef.current = false;
|
inFlightRef.current = false;
|
||||||
if (mounted) setLoading(false);
|
if (mounted) setLoading(false);
|
||||||
|
|||||||
@ -125,7 +125,7 @@ export class AppComponent {
|
|||||||
|
|
||||||
// Iterate through possible values of n1, which must be multiples of x, at least y, and not more than z
|
// Iterate through possible values of n1, which must be multiples of x, at least y, and not more than z
|
||||||
for (let n1 = y; n1 <= ml - y && n1 <= z; n1 += x) {
|
for (let n1 = y; n1 <= ml - y && n1 <= z; n1 += x) {
|
||||||
let n2 = ml - n1;
|
const n2 = ml - n1;
|
||||||
// Ensure n2 is also a multiple of x, n2 >= y, and n2 <= z
|
// Ensure n2 is also a multiple of x, n2 >= y, and n2 <= z
|
||||||
if (n2 % x === 0 && n2 >= y && n2 <= z) {
|
if (n2 % x === 0 && n2 >= y && n2 <= z) {
|
||||||
results.push([n1, n2]);
|
results.push([n1, n2]);
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user