Last active
October 25, 2024 19:18
-
-
Save PlugFox/80541bd650f17a0796780f7f953a1dda to your computer and use it in GitHub Desktop.
Sort numbers from 10 to 100 by their English word representation
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
/* | |
* Sort numbers from 10 to 100 by their English word representation | |
* https://gist.github.com/PlugFox/80541bd650f17a0796780f7f953a1dda | |
* https://dartpad.dev?id=80541bd650f17a0796780f7f953a1dda | |
* Mike Matiunin <[email protected]>, 25 October 2024 | |
*/ | |
const units = [ | |
'zero', | |
'one', | |
'two', | |
'three', | |
'four', | |
'five', | |
'six', | |
'seven', | |
'eight', | |
'nine', | |
'ten', | |
'eleven', | |
'twelve', | |
'thirteen', | |
'fourteen', | |
'fifteen', | |
'sixteen', | |
'seventeen', | |
'eighteen', | |
'nineteen', | |
]; | |
const tens = [ | |
'', // 0..9 are covered by units | |
'', // 10..19 are covered by units | |
'twenty', | |
'thirty', | |
'forty', | |
'fifty', | |
'sixty', | |
'seventy', | |
'eighty', | |
'ninety', | |
]; | |
// Convert number to words | |
String n2w(int number) => switch (number) { | |
<= 19 => units[number], | |
< 100 when number % 10 == 0 => tens[number ~/ 10], | |
< 100 => '${tens[number ~/ 10]}-${units[number % 10]}', | |
100 => 'one hundred', | |
_ => 'number is out of range', | |
}; | |
void main() => print([ | |
for (int i = 10; i <= 100; i++) (i, n2w(i)), | |
]..sort((a, b) => a.$2.compareTo(b.$2))); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment