Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
101 changes: 101 additions & 0 deletions solutions/c/wordy/1/wordy.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
#include "wordy.h"
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static inline char get_op(const char *token);
static inline int calculate(int n1, int n2, char op, bool *error);

bool answer(const char *question, int *result){
if (!question || !result) return false;

size_t len = strlen(question);

if (len < sizeof("What is _?") - 1) return false;

int n1 = 0;
int n2 = 0;
char op = 0;

char *q = malloc(len + 1);
if (!q) return false;

memcpy(q, question, len + 1);

char delims[] = {' ', '?'};
char *token = strtok(q, delims);

if (strcmp(token, "What") != 0) goto FAIL;
token = strtok(NULL, delims);
if (strcmp(token, "is") != 0) goto FAIL;

token = strtok(NULL, delims);
if (sscanf(token, "%d", &n1) == 0) goto FAIL;

bool error = false;
do {
token = strtok(NULL, delims);
if (!token) break;
op = get_op(token);
if (!op) goto FAIL;

if (op == '*' || op == '/') {
token = strtok(NULL, delims);
if (!token || strcmp(token, "by") != 0) goto FAIL;
}

token = strtok(NULL, delims);
if (!token) goto FAIL;
if (sscanf(token, "%d", &n2) == 0) goto FAIL;

n1 = calculate(n1, n2, op, &error);
if (error) goto FAIL;
} while(token);

free(q);
*result = n1;
return true;
FAIL:
free(q);
return false;
}

static inline int calculate(int n1, int n2, char op, bool *error){
*error = false;
switch (op) {
case '+':
return n1 + n2;
case '-':
return n1 - n2;
case '*':
return n1 * n2;
case '/':
if (n2 != 0) return n1 / n2;
else {*error = true; return 0;}
default:
*error = true;
return 0;
}
}

static inline char get_op(const char *token) {
if (!token || !token[0]) return '\0';

switch (token[0]) {
case 'p':
if (strcmp(token, "plus") == 0) return '+';
break;
case 'm':
if (token[1] == 'i') {
if (strcmp(token, "minus") == 0) return '-';
} else if (token[1] == 'u') {
if (strcmp(token, "multiplied") == 0) return '*';
}
break;
case 'd':
if (strcmp(token, "divided") == 0) return '/';
break;
}
return '\0';
}
8 changes: 8 additions & 0 deletions solutions/c/wordy/1/wordy.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
#ifndef WORDY_H
#define WORDY_H

#include <stdbool.h>

bool answer(const char *question, int *result);

#endif