Commit 40e3f7b7 authored by Anthony REY's avatar Anthony REY

Roman calculator kata

parent 26b25a6a
......@@ -20,3 +20,4 @@ include:
- local: "/exceptions/.gitlab-ci.yml"
- local: "/puissance-4/.gitlab-ci.yml"
- local: "/trip-service-kata-typescript/.gitlab-ci.yml"
- local: "/roman-calculator/.gitlab-ci.yml"
......@@ -43,3 +43,4 @@ Ce dépôt Git a pour but de partager les différents ateliers pouvant être ré
| [Exceptions](/exceptions) | Code&coffee | Facile |
| [Puissance 4](/puissance-4) | Kata | Moyenne |
| [Trip service (TypeScript)](/trip-service-kata-typescript) | Kata | Moyenne |
| [Roman calculator](/roman-calculator) | Kata | Moyenne |
module.exports = {
root: true,
env: {
node: true,
},
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:import/errors',
'plugin:import/warnings',
'plugin:import/typescript',
],
plugins: ['prettier', '@typescript-eslint'],
rules: {
quotes: ['error', 'single', { avoidEscape: true }],
'comma-dangle': [
'error',
{
arrays: 'always-multiline',
objects: 'always-multiline',
imports: 'always-multiline',
exports: 'always-multiline',
functions: 'never',
},
],
'import/order': [
'error',
{
alphabetize: {
order: 'asc',
caseInsensitive: true,
},
'newlines-between': 'always',
},
],
'prettier/prettier': [
'error',
{
singleQuote: true,
trailingComma: 'es5',
printWidth: 140,
},
],
},
settings: {
'import/resolver': {
typescript: {
alwaysTryTypes: true,
},
},
'import/core-modules': ['sinon'],
},
parserOptions: {
parser: '@typescript-eslint/parser',
},
overrides: [
{
files: ['**/__tests__/*.{j,t}s?(x)', '**/*.spec.{j,t}s?(x)'],
env: {
jest: true,
},
},
{
files: ['**/*.ts', '**/*.tsx'],
rules: {
'no-unused-vars': ['off'],
'no-undef': ['off'],
},
},
],
};
roman-calculator:
variables:
PROJECT_FOLDER: "roman-calculator"
extends: .node14
only:
refs:
- master
- merge_requests
changes:
- ".gitlab-common-ci.yml"
- "roman-calculator/**/*"
# Roman Calculator
Résolution du kata [Roman Calculator](https://codingdojo.org/kata/RomanCalculator/) en TypeScript.
- **Auteurs** : Arnaud FREISMUTH et Anthony REY
- **Date** : 26/10/2020
- **Langage** : TypeScript
- **Niveau** : Moyen
- **Replay** : [Kata Roman Calculator avec Arnaud et Anthony](https://www.youtube.com/watch?v=tKMWzLhvOG0)
# Roman Calculator
## About this Kata
[CodersDojoSweden](/dojo/CodersDojoSweden) , running in Linköping, was
looking for a new Kata which was sufficiently simple to get beginners up
and running. [ThomasNilsson](/people/ThomasNilsson) suggested a
calculator using Roman numerals.
## Problem Description
"As a Roman Bookkeeper I want to add Roman numbers because doing it
manually is too tedious." Given the Roman numerals, (IVXLCDM which means
one, five, ten, fifty, hundred, fivehundred and a thousand
respectively), create two numbers and add them. As we are in Rome there
is no such thing as decimals or int, we need to do this with the
strings. An example would be "XIV" + "LX" = "LXXIV"
There are some rules to a Roman number:
- Numerals can be concatenated to form a larger numeral ("XX" + "II"
= "XXII")
- If a lesser numeral is put before a bigger it means subtraction of
the lesser from the bigger ("IV" means four, "CM" means ninehundred)
- If the numeral is I, X or C you can't have more than three ("II" +
"II" = "IV")
- If the numeral is V, L or D you can't have more than one ("D" + "D"
= "M")
## Clues
String grouping and concatenation is key to solving this kata. But
remember the rule that lesser numerals can preceede bigger ones.
## Suggested Test Cases
The first test case(s) are pretty easy. I won't put the test cases here
since I feel this kata is one of the better ones I have done when it
comes to practicing finding out what the next test case is.
## Comments from those who are working on this Kata
When I invented it I did not know how well it would work. I was
pleasantly surprised to see it work out to be a kata very focused on
finding test cases. -- [ThomasNilsson](/people/ThomasNilsson)
------------------------------------------------------------------------
This kata does not immediately show the "behaviour" aspect as does e.g.
the Bowling kata. By this I mean the behaviour of a class under test, as
opposed to testdriving a single method. However, in the Linköping dojo,
we decided on adding this aspect by changing the story to "As a Polish
born Roman Accountant..." and thereby introducing the Polish reverse
notation to the calculation. The first test would then become:
public void testOnePlusOneShouldEqualTwo() {
RomanPolishCalculator calculator = new RomanPolishCalculator();
calculator.enter("I");
calculator.enter("I");
assertEquals("II", calculator.add());
}
And we also decided to add this aspect on an already running partial
solution in the middle of the kata. This creates the situation of
refactoring the API into another structure. We'll see how this turns
out. -- [ThomasNilsson](/people/ThomasNilsson)
------------------------------------------------------------------------
*Here is a CoffeeScript implementation (both forward and backwards).*
*I've just been learning CS and working with Node.js, npm, and Grunt.
Here's a link to my GitHub where it's hosted :
https://github.com/tebriel/RomanNumeralConverterKata*
--ChrisMoultrie .
# Roman Numerals
## About this Kata
I wasn't there, but I believe this Kata was performed at XP2001 by Kent Beck. Here is [\[a video of Karl Scotland doing this Kata in Excel at agile 2008\]](http://www.infoq.com/presentations/TDD-Managers-Nicolette-Scotland)
Here is [\[a video of JonJagger doing this Kata in Ruby using CyberDojo\]](http://vimeo.com/15104374)
Difficulty - Easy.
## Problem Description
The Romans were a clever bunch. They conquered most of Europe and ruled it for hundreds of years. They invented concrete and straight roads and even bikinis [\[1\]](http://sights.seindal.dk/sight/456_Roman_Villa_of_Piazza_Armerina.html).
One thing they never discovered though was the number zero. This made writing and dating extensive histories of their exploits slightly more challenging, but the system of numbers they came up with is still in use today. For example the BBC uses Roman numerals to date their programmes.
The Romans wrote numbers using letters : `I`, `V`, `X`, `L`, `C`, `D`, `M`. (notice these letters have lots of straight lines and are hence easy to hack into stone tablets)
### Part I
The Kata says you should write a function to convert from normal numbers to Roman Numerals: eg
1 --> I
10 --> X
7 --> VII
etc.
For a full description of how it works, take a look at [\[this useful reference website\]](http://www.novaroma.org/via_romana/numbers.html) : which includes an implementation of the Kata in javascript.
There is no need to be able to convert numbers larger than about 3000. (The Romans themselves didn't tend to go any higher)
### Part II
Write a function to convert in the other direction, ie numeral to digit
## Clues
- Can you make the code really beautiful and highly readable?
- does it help to break out lots of small named functions from the main function, or is it better to keep it all in one function?
- if you don't know an algorithm to do this already, can you derive one using strict TDD?
- does the order you take the tests in affect the final design of your algorithm?
- Would it be better to work out an algorithm first before starting with TDD?
- if you do know an algorithm already, can you implement it using strict TDD?
- Can you think of another algorithm?
- what are the best data structures for storing all the numeral letters? (`I`, `V`, `D`, `M` etc)
- can you define the test cases in a csv file and use FIT, or generate test cases in xUnit?
- what is the best way to verify your tests are correct?
## Comments from those who are working on this Kata
We tackled this Kata at this [GothPy081007](/record/GothPy081007) meeting -- [EmilyBache](/people/EmilyBache)
[\[Here's a Scala solution\]](http://blog.crisp.se/hansbrattberg/2010/08/10/1281424295367.html), -- HansBrattberg
Found a [\[F\# solution\]](http://github.com/hibri/f_sharp_roman_numeral_converter/blob/master/Dojo.FSharp/Roman.fs) and a [\[tidy Ruby one\]](http://github.com/ruby-fatecsp/dojos/blob/8cb15023eec6d4a5c9cdcf1723adff1ed5864a03/roman_to_numerals/lib/roman_to_num.rb) at github.
[\[Implementation\]](https://github.com/froderik/roman_numeral_katas) in
ruby, java and clojure along with acceptance tests written in ruby and
interacting with the command line. Would be nice with some additional
languages. - [FredrikRubensson](/people/FredrikRubensson)
[\[Here's a JavaScript solution\]](https://github.com/machi1990/num_to_rom) at Github
module.exports = {
roots: ['<rootDir>/src'],
transform: {
'^.+\\.tsx?$': 'ts-jest',
},
testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$',
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
testEnvironment: 'node',
};
This source diff could not be displayed because it is too large. You can view the blob instead.
{
"name": "roman-calculator",
"version": "1.0.0",
"description": "Template TS kata",
"main": "src/index.ts",
"dependencies": {
"@types/jest": "^26.0.15",
"@typescript-eslint/eslint-plugin": "^4.6.0",
"@typescript-eslint/parser": "^4.6.0",
"eslint": "^7.12.0",
"eslint-import-resolver-typescript": "^2.3.0",
"eslint-plugin-import": "^2.22.1",
"eslint-plugin-prettier": "^3.1.4",
"jest": "^26.6.1",
"prettier": "^2.1.2",
"ts-jest": "^26.4.2",
"typescript": "^4.0.3"
},
"scripts": {
"test": "jest",
"test:watch": "jest --watch",
"test:watch:all": "jest --watchAll",
"eslint:ci": "eslint './**/*.{ts,js}'",
"eslint": "eslint './**/*.{ts,js}' --fix"
},
"author": "Anthony REY",
"license": "MIT"
}
const ARABIC_TO_ROMAN = {
1: 'I',
4: 'IV',
5: 'V',
9: 'IX',
10: 'X',
40: 'XL',
50: 'L',
90: 'XC',
100: 'C',
400: 'CD',
500: 'D',
900: 'CM',
1000: 'M',
};
const toRoman = (arabic: number): string => {
if (arabic === 0) {
return '';
}
const [foundArabic, foundRoman] = Object.entries(ARABIC_TO_ROMAN)
.reverse()
.find(([number]) => arabic >= +number);
return foundRoman.concat(toRoman(arabic - +foundArabic));
};
const toArabic = (roman: string): number => {
if (roman.length === 0) {
return 0;
}
const [foundArabic, foundRoman] = Object.entries(ARABIC_TO_ROMAN)
.reverse()
.find(([, romanNumber]) => roman.startsWith(romanNumber));
return +foundArabic + toArabic(roman.substring(foundRoman.length));
};
const romanSum = (first: string, second: string) => toRoman(toArabic(first) + toArabic(second));
const romanMultiply = (first: string, second: string): string => toRoman(toArabic(first) * toArabic(second));
const romanOperation = (operation: string): string => {
const [first, second] = operation.split(/[+*]/).map((string) => string.trim());
if (operation.includes('*')) {
return romanMultiply(first, second);
}
return romanSum(first, second);
};
describe('Roman Calculator', () => {
describe('For Arabic', () => {
it('Should be empty for 0', () => {
expect(toRoman(0)).toBe('');
});
it('Should be I for 1', () => {
expect(toRoman(1)).toBe('I');
});
it('Should be III for 3', () => {
expect(toRoman(3)).toBe('III');
});
it('Should be IV for 4', () => {
expect(toRoman(4)).toBe('IV');
});
it('Should be V for 5', () => {
expect(toRoman(5)).toBe('V');
});
it('Should be VI for 6', () => {
expect(toRoman(6)).toBe('VI');
});
it('Should be VIII for 8', () => {
expect(toRoman(8)).toBe('VIII');
});
it('Should be IX for 9', () => {
expect(toRoman(9)).toBe('IX');
});
it('Should be X for 10', () => {
expect(toRoman(10)).toBe('X');
});
it('Should be XL for 40', () => {
expect(toRoman(40)).toBe('XL');
});
it('Should be L for 50', () => {
expect(toRoman(50)).toBe('L');
});
it('Should be XC for 90', () => {
expect(toRoman(90)).toBe('XC');
});
it('Should be C for 100', () => {
expect(toRoman(100)).toBe('C');
});
it('Should be CD for 400', () => {
expect(toRoman(400)).toBe('CD');
});
it('Should be D for 500', () => {
expect(toRoman(500)).toBe('D');
});
it('Should be CM for 900', () => {
expect(toRoman(900)).toBe('CM');
});
it('Should be M for 1000', () => {
expect(toRoman(1000)).toBe('M');
});
it('Should be MMMMDCCCLXXXVIII for 4888', () => {
expect(toRoman(4888)).toBe('MMMMDCCCLXXXVIII');
});
it('Should be MCMXCVIII for 1998', () => {
expect(toRoman(1998)).toBe('MCMXCVIII');
});
});
describe('For Roman', () => {
it('Should be 0 for empty string', () => {
expect(toArabic('')).toBe(0);
});
it('Should be 1 for I', () => {
expect(toArabic('I')).toBe(1);
});
it('Should be 3 for III', () => {
expect(toArabic('III')).toBe(3);
});
it('Should be 4 for IV', () => {
expect(toArabic('IV')).toBe(4);
});
it('Should be 5 for V', () => {
expect(toArabic('V')).toBe(5);
});
it('Should be 6 for VI', () => {
expect(toArabic('VI')).toBe(6);
});
it('Should be 1998 for MCMXCVIII', () => {
expect(toArabic('MCMXCVIII')).toBe(1998);
});
});
describe('Calculate', () => {
it('Should sum III and IV', () => {
expect(romanSum('III', 'IV')).toBe('VII');
});
it('Should multiply VI and VII', () => {
expect(romanMultiply('VI', 'VII')).toBe('XLII');
});
it('Should sum VIII and I', () => {
expect(romanOperation('VIII + I')).toBe('IX');
});
it('Should sum IX and IX', () => {
expect(romanOperation('IX * IX')).toBe('LXXXI');
});
});
});
{
"compilerOptions": {
"target": "ES2019",
"module": "commonjs",
"noImplicitAny": true,
"removeComments": true,
"preserveConstEnums": true,
"outFile": "dist/main.js",
"sourceMap": true
},
"include": [
"src/**/*"
],
"exclude": [
"node_modules",
"**/*.spec.ts"
]
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment