-
Notifications
You must be signed in to change notification settings - Fork 7
/
Imei-Validator.linq
55 lines (40 loc) · 950 Bytes
/
Imei-Validator.linq
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<Query Kind="Program">
<Namespace>Xunit</Namespace>
</Query>
#load "xunit"
void Main()
{
ValidateIMEINumber(Valid).Dump();
ValidateIMEINumber(Invalid).Dump();
RunTests();
}
const string Valid = "358981879372208";
const string Invalid = "358981879372999";
public bool ValidateIMEINumber(string Imei)
{
if (!long.TryParse(Imei, out _)) /* IMEIs are longer than int.MaxValue */
{
return false;
}
return CheckLuhnNumber(Imei.Select(x => x - '0'));
}
private static bool CheckLuhnNumber(IEnumerable<int> number)
{
int iDigit = 0;
int iSum = 0;
bool bIsOdd = false;
foreach(int item in number)
{
iDigit = item;
if (bIsOdd == true)
iDigit *= 2;
iSum += iDigit / 10;
iSum += iDigit % 10;
bIsOdd = !bIsOdd;
}
return (iSum % 10 == 0);
}
#region private::Tests
[Fact] void Valid_Imei() => Assert.True(ValidateIMEINumber(Valid));
[Fact] void Invalid_Imei() => Assert.False(ValidateIMEINumber(Invalid));
#endregion