Level 1 : Project 3
Plane tickets from an airline show an 11- digit code preceded by a capital letter.
Example: U19586900462.
To verify the authenticity of a ticket, replace the letter of the code by its alphabetical rank to obtain a number of 12 or 13 digits.
If the remainder of the division by 9 of the sum of the digits of this number is equal to 8 , this ticket is authentic, otherwise it's a fake ticket.
Example:
The ticket with the code "U19586900462" is authentic. Indeed,
-
The letter "U" has alphabetical rank 21.
-
The number formed will be: " 21 19586900462".
-
The sum of the digits of this number is 2 + 1 + 1 + 9 + 5 + 8 + 6 + 9 + 0 + 0 + 4 + 6 + 2 = 53.
-
The remainder of the division of 53 by 9 is equal to 8 .
We propose to write a Dart program which allows to verify the authenticity of a ticket from its code.
Solution:
import 'dart:io';
String typeCode() {
String code;
int codeNum;
do {
print("Enter the Code of the plane ticket");
code = stdin.readLineSync();
//checking the first character of the code and its length
if ((code.length == 12) &&
(code.codeUnitAt(0) >= 65) && //>='A'
(code.codeUnitAt(0) <= 90)) {
//<='Z'
//checking if the rest of the code is numeric
codeNum = int.tryParse(code.substring(1));
//if codeNum == null then the rest is not numeric
}
} while (codeNum == null);
return code;
}
void verifCode(String code) {
int firstLetterRank = code.codeUnitAt(0) - 64;
int sum;
if (firstLetterRank > 9) //a two-digit number
sum = (firstLetterRank % 10) + (firstLetterRank ~/ 10);
else //a one-digit number
sum = firstLetterRank;
for (int i = 1; i <= 11; i++) {
sum += int.parse(code[i]);
}
if (sum % 9 == 8)
print("Authentic");
else
print("Fake");
}
void main() {
var code = typeCode();
verifCode(code);
}
U19586900462
Authentic
U73985019381
Fake