60 lines
2.0 KiB
C
60 lines
2.0 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <stdint.h>
|
|
#include <stdbool.h>
|
|
|
|
// Returns -1 if a string is not a number (e.g. 'two')
|
|
// Otherwise, returns the number.
|
|
// Only works for single digits.
|
|
// Only accepts lower case.
|
|
int8_t parse_num(char *str)
|
|
{
|
|
const char *num_strings[10] = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
|
|
|
|
// The lengths of the strings above,
|
|
const uint8_t num_string_lens[10] = { 4, 3, 3, 5, 4, 4, 3, 5, 5, 4 };
|
|
|
|
bool possible_nums[10] = { [0 ... 9] = true };
|
|
uint8_t num_idx = 0;
|
|
uint8_t char_incriment = 0;
|
|
char current;
|
|
bool result_still_possible = false;
|
|
|
|
for (char_incriment = 0; char_incriment < 6; char_incriment++)
|
|
{
|
|
// Grab out next character in the string
|
|
current = *(str + char_incriment);
|
|
|
|
for (num_idx = 0; num_idx < 10; num_idx++)
|
|
{
|
|
if (!possible_nums[num_idx]) continue;
|
|
|
|
// If we have passed the end of our number string and every character has matched,
|
|
// then we return our valid character.
|
|
if (char_incriment == num_string_lens[num_idx] && possible_nums[num_idx]) return num_idx;
|
|
|
|
// If the character is not the letter it should be, disqualify this number.
|
|
// e.g. if num_idx == 1 and char_incriment == 2, current should equal 'e'
|
|
// because 'e' is the 3rd number in the word 'one.'
|
|
if (current != num_strings[num_idx][char_incriment]) possible_nums[num_idx] = false;
|
|
else result_still_possible = true;
|
|
}
|
|
if (!result_still_possible) return -1;
|
|
}
|
|
|
|
return -1;
|
|
}
|
|
|
|
int main(int argc, char **argv) {
|
|
|
|
const char *num_strings[10] = { "zerorr", "oneqw", "twoqw", "threere", "fourer", "fiveer", "sixer", "sevener", "eighter", "nineer" };
|
|
|
|
uint8_t i = 0;
|
|
|
|
for (i = 0; i < 10; i++)
|
|
{
|
|
printf("%d\n", parse_num(num_strings[i]));
|
|
}
|
|
|
|
return 0;
|
|
} |