Skip to content

Instantly share code, notes, and snippets.

@mauricioaniche
Created May 30, 2017 09:25
Show Gist options
  • Save mauricioaniche/67543e9dba7eea7785713ee06a563ca0 to your computer and use it in GitHub Desktop.
Save mauricioaniche/67543e9dba7eea7785713ee06a563ca0 to your computer and use it in GitHub Desktop.
package tdd;
import java.util.HashMap;
import java.util.Map;
/**
* Created by mauricioaniche on 26/05/2017.
*/
public class RomanConverter {
private static Map<String, Integer> table;
static {
table = new HashMap<>();
table.put("I", 1);
table.put("V", 5);
table.put("X", 10);
table.put("L", 50);
table.put("C", 100);
table.put("D", 500);
table.put("M", 1000);
}
public int convert(String romanNumeral) {
int finalValue = 0;
for(int i = 0; i < romanNumeral.length(); i++) {
int currentValue = roman(romanNumeral.charAt(i));
boolean notLastDigit = i < romanNumeral.length() - 1;
if(notLastDigit && roman(romanNumeral.charAt(i+1)) > currentValue) {
currentValue *= -1;
}
finalValue += currentValue;
}
return finalValue;
}
private Integer roman(char romanNumeral) {
return table.get(String.valueOf(romanNumeral));
}
}
package tdd;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Created by mauricioaniche on 26/05/2017.
*/
public class RomanConverterTest {
@ParameterizedTest(name = "roman numbers with a single digit")
@CsvSource({"I, 1", "V, 5", "X, 10"})
void simpleRomanNumber(String romanNumber, int value) {
int number = new RomanConverter().convert(romanNumber);
assertThat(number).isEqualTo(value);
}
@ParameterizedTest(name="roman number with many digits: {0}")
@CsvSource({"II, 2", "III, 3", "VII, 7", "CLXIII, 163"})
void manyDigits(String romanNumber, int value) {
int number = new RomanConverter().convert(romanNumber);
assertThat(number).isEqualTo(value);
}
@ParameterizedTest(name="inverse order: {0}")
@CsvSource({"IV, 4", "XIV, 14", "CDXXXII, 432"})
void inverseOrder(String romanNumber, int value) {
int number = new RomanConverter().convert(romanNumber);
assertThat(number).isEqualTo(value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment