Skip to content

Instantly share code, notes, and snippets.

@JasperEssien2
Created April 23, 2022 15:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JasperEssien2/d81bd2804bd83c26acb4f6731efaa950 to your computer and use it in GitHub Desktop.
Save JasperEssien2/d81bd2804bd83c26acb4f6731efaa950 to your computer and use it in GitHub Desktop.
My solution to Roman Numeral Kata code challenge
void main(List<String> arguments) {
print("TOTAL ==== ${convert("MCMXLIV")}"); //Expect 1944
}
final romanRepresentation = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000,
};
int convert(String figure) {
figure = figure.toUpperCase();
final retainedList = <int>[];
final figureList = figure.split("");
for (int i = 0; i < figureList.length; i++) {
String? nextRoman = _hasNoNext(i, figureList) ? null : figureList[i + 1];
String currentRoman = figureList[i];
if (nextRoman == null) {
retainedList.add(romanRepresentation[currentRoman]!);
break;
}
if (isLesser(currentRoman, nextRoman)) {
final retainValue =
romanRepresentation[nextRoman]! - romanRepresentation[currentRoman]!;
retainedList.add(retainValue);
/// Skip to next
i = i + 1;
} else {
retainedList.add(romanRepresentation[currentRoman]!);
}
}
int total = retainedList.fold<int>(
0, (previousValue, element) => previousValue + element);
return total;
}
bool _hasNoNext(int i, List<String> figureList) => i + 1 == figureList.length;
bool isLesser(String current, String target) {
return romanRepresentation[current]! < romanRepresentation[target]!;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment