summaryrefslogtreecommitdiffstats
path: root/snc.c
blob: d42dce229c7801d6ec42411b4c233006ef370db0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/***
	This file is part of Simple numbers converter.

	Copyright (C) 2021 Aleksandr D. Goncharov (Joursoir) <chat@joursoir.net>

	Simple numbers converter is free software; you can redistribute it
	and/or modify it under the terms of the GNU General Public License
	as published by the Free Software Foundation; either version 2
	of the License, or (at your option) any later version.

	Simple numbers converter is distributed in the hope that it will be
	useful, but WITHOUT ANY WARRANTY; without even the implied warranty
	of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program; if not, see <http://www.gnu.org/licenses/>.
***/

#include <stdio.h>

#include "snc.h"

int getRomanValue(char symbol)
{
	switch(symbol) {
		case 'I': return SNC_ROMAN_I; // have triple notation
		case 'V': return SNC_ROMAN_V;
		case 'X': return SNC_ROMAN_X; // have triple notation
		case 'L': return SNC_ROMAN_L;
		case 'C': return SNC_ROMAN_C; // have triple notation
		case 'D': return SNC_ROMAN_D;
		case 'M': return SNC_ROMAN_M; // have triple notation
	}
	return 0;
}

int romanToArabic(char *str)
{
	int answer = 0;
	int last_value = 0;
	int amount_char = 0;
	while(*str)
	{
		int cur_value = getRomanValue(*str);
		if(cur_value == 0)
			return -1;
		else if(last_value == cur_value || last_value == 0) {
			answer += cur_value;
			amount_char++;
		}
		else if(last_value > cur_value) {
			answer += cur_value;
			amount_char = 1;
		}
		else if(last_value < cur_value) {
			if(last_value * 10 < cur_value)
				return -1;
			else if(last_value == SNC_ROMAN_V ||
					last_value == SNC_ROMAN_L || last_value == SNC_ROMAN_D)
				return -1;
			
			answer += cur_value - 2 * last_value;
			if(amount_char > 1)
				return -1;
			amount_char = 1;
		}
		last_value = cur_value;

		if(amount_char > 3)
			return -1;
		else if(cur_value == SNC_ROMAN_V ||
				cur_value == SNC_ROMAN_L || cur_value == SNC_ROMAN_D) {
			if(amount_char > 1) return -1;
		}

		str++;
	}

	return answer;
}

int main(int argc, char *argv[])
{
	if(argc < 2)
		return printf("Simple numbers converter\n"
					"\n"
					"Synopsis: snc [number]\n");

	int answer = romanToArabic(argv[1]);
	if(answer == -1) printf("ERROR! %s is not roman number\n", argv[1]);
	else printf("answer: %d\n", answer);

	return 0;
}