Created
July 23, 2014 11:09
-
-
Save yemrekeskin/897d974fe6a79326eb29 to your computer and use it in GitHub Desktop.
Random Turkish Identification Number Generator with c#
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
using System; | |
using System.Collections; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
namespace Samples | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var result = TCIdGenerator(); | |
Console.WriteLine(result); | |
Console.WriteLine("is valid : {0}",ValidTurkishIdNo(result)); | |
Console.WriteLine("is valid : {0}", ValidTurkishIdNo("57774200136")); | |
Console.ReadLine(); | |
} | |
public static string TCIdGenerator() | |
{ | |
string a = getRandomNumber(); | |
var x = a.ToCharArray(); | |
int[] b = new int[10]; | |
for (int i = 0; i < x.Length; i++) | |
{ | |
b[i] = Convert.ToInt32(x.GetValue(i).ToString(), 10); | |
} | |
var c = b[0] + b[2] + b[4] + b[6] + b[8]; | |
var d = b[1] + b[3] + b[5] + b[7]; | |
var e = (7 * c - d) % 10; | |
var result = a + ("" + e) + ("" + (d + c + e) % 10); | |
if (!ValidTurkishIdNo(result)) | |
TCIdGenerator(); | |
return result; | |
} | |
private static string getRandomNumber() | |
{ | |
Random rnd = new Random(); | |
var result = "" + Math.Floor(900000001 * rnd.Next() + 1e8); | |
int n; | |
bool isNumeric = int.TryParse(result, out n); | |
if (!isNumeric || result.Substring(0, 1) == "-") | |
getRandomNumber(); | |
return result; | |
} | |
public static bool ValidTurkishIdNo(string TCNo) | |
{ | |
int[] TC = new int[11]; | |
for (int i = 0; i < 11; i++) | |
{ | |
string a = TCNo[i].ToString(); | |
TC[i] = Convert.ToInt32(a); | |
} | |
int singurals = 0; | |
int plurals = 0; | |
for (int k = 0; k < 9; k++) | |
{ | |
if (k % 2 == 0) | |
singurals += TC[k]; | |
else if (k % 2 != 0) | |
plurals += TC[k]; | |
} | |
int t1 = (singurals * 3) + plurals; | |
int c1 = (10 - (t1 % 10)) % 10; | |
int t2 = c1 + plurals; | |
int t3 = (t2 * 3) + singurals; | |
int c2 = (10 - (t3 % 10)) % 10; | |
if (c1 == TC[9] && c2 == TC[10]) | |
return true; | |
else | |
return false; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment