Created
April 23, 2022 15:22
-
-
Save JasperEssien2/d81bd2804bd83c26acb4f6731efaa950 to your computer and use it in GitHub Desktop.
My solution to Roman Numeral Kata code challenge
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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