Skip to content

Instantly share code, notes, and snippets.

@PlugFox
Last active October 25, 2024 19:18
Show Gist options
  • Save PlugFox/80541bd650f17a0796780f7f953a1dda to your computer and use it in GitHub Desktop.
Save PlugFox/80541bd650f17a0796780f7f953a1dda to your computer and use it in GitHub Desktop.
Sort numbers from 10 to 100 by their English word representation
/*
* 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